package com.socool.sinofaith.ui;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import org.w3c.dom.Text;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnLastItemVisibleListener;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.socool.sinafaith.zbar.ZBarMainActivity;
import com.socool.sinofaith.R;
import com.socool.sinofaith.SocoolApplication;
import com.socool.sinofaith.dao.QuestionAnswerDao;
import com.socool.sinofaith.dao.SifQuestionOptionsDao;
import com.socool.sinofaith.dao.SifSubTaskDao;
import com.socool.sinofaith.dao.SifSubTemplateDao;
import com.socool.sinofaith.dao.SifTaskDao;
import com.socool.sinofaith.dao.SifTaskQuestionDao;
import com.socool.sinofaith.jsonparse.HttpJsonAdapter;
import com.socool.sinofaith.model.AnswerReq;
import com.socool.sinofaith.model.BaseMessage;
import com.socool.sinofaith.model.QuestionAnswerBean;
import com.socool.sinofaith.model.QuestionAnswerReqBean;
import com.socool.sinofaith.model.SifQuestionOptionsBean;
import com.socool.sinofaith.model.SifSubTaskBean;
import com.socool.sinofaith.model.SifSubTemplateBean;
import com.socool.sinofaith.model.SifTaskBean;
import com.socool.sinofaith.model.SifTaskQuestionBean;
import com.socool.sinofaith.model.SynTaskResponse;
import com.socool.sinofaith.model.SynTaskResponse.SynTaskBean.SynSubtaskBean;
import com.socool.sinofaith.model.UpLoadFileBean;
import com.socool.sinofaith.util.BGSharedPreference;
import com.socool.sinofaith.util.ConstansJsonUrl;
import com.socool.sinofaith.util.S;
import com.socool.sinofaith.util.SinofaithUtil;
import com.socool.sinofaith.view.LoadingDialog;
import com.socool.sinofaith.view.MyDialog;
import com.socool.sinofaith.view.ProgressDialog;
import com.socool.sinofaith.view.TitlePopup;
import com.socool.sinofaith.view.TitlePopup.OnPopupItemClickListener;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.Html;
import android.text.TextUtils;
import android.text.TextUtils.TruncateAt;
import android.text.TextWatcher;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.AjaxParams;
import net.tsz.afinal.utils.Utils;

/**
 * 进入
 * 
 * @author jiang
 *
 */
public class ChildTaskActivity extends Activity {

	final int IMAGE_MAX_SIZE = 1024;

	private static int ALREADY_ANSWER = 1;
	private static int NOT_ANSWER = 2;
	private static int ALREADY_SUBMIT = 3;
	private int[] location = new int[2];
	private String tag = "TAG";
	// ActionBarHelperBase mActionBarHelperBase;
	private TextView finish, automatic, manual, taskname, mark;
	// 判断是否第一次答题
	private boolean isFirstDo;

	private Button btn_onechoose;
	private String UserMobile;

	// 获取图片
	private ContentResolver mContentResolver;

	private int showdetail = 0x10;
	private int notshowdetail = 0x11;
	// 是否可以拍照
	private boolean isTake = false;
	// 扫描
	private Button btn_scan;
	// 1全选 2全不选 3自由选
	private int isWhole = 3;
	// 遮罩层
	private RelativeLayout rl_bulr;
	private ChildTaskAdapter mChildTaskAdapter;

	private PullToRefreshListView mListView;

	private TextView tv_back, tv_title, tv_detail;
	private ImageView iv_detail;

	private ArrayList<String> popupItems;
	private String Task_Name, taskid, subtaskid, tempjson, taskName;
	private ArrayList<QuestionAnswerBean> totalAnswerlist, finishAnswerlist, autoAnswerlist, manualAnswerlist,
			answerlist, remindsList;
	private ArrayList<QuestionAnswerBean> markAnswerlist;
	private List<SifSubTaskBean> subTaskBeans;
	private SifTaskBean taskBean;

	private QuestionAnswerReqBean answerReqBean;
	private ArrayList<AnswerReq> SubAnswer;
	private QuestionAnswerDao answerDao;

	private Button rushTaskButton, btnSearch, btnClear;
	// 是否显示check标记
	private boolean checkflag = false;

	private int currentIndex = 0;
	// 按钮按下的那个题目的item
	private String StempIndex = "";
	// 第一个问题的id
	private String questionIndex = "";
	// 第二个问题的id
	private String secondQuestionIndex = "";
	// 根据标题 特殊处理
	private boolean isSpecialFlag = false;

	String flagtemp = "1";

	List<String[]> strings;

	private TextView alreadyAnswer, notAnswer, alreadySubmit;

	private int count, totalcount, failcount, failtotalcount = 0;
	private String end;

	private LoadingDialog mLoadingDialog;

	private List<AjaxParams> paramsList = new ArrayList<AjaxParams>();

	Dialog dialog;

	Lock lock = new ReentrantLock();

	int type = 0;

	int fcount = 0;

	private String carDetail = "全部";

	HashMap<String, String> firstParamsMap = new HashMap<String, String>();

	int num = 0;

	// 底部状态
	int bottomType = -1;

	private TitlePopup mPopup;
	private Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {

			switch (msg.what) {
			case 0x01:
				rl_bulr.setVisibility(View.VISIBLE);
				break;

			case 0x02:
				rl_bulr.setVisibility(View.GONE);
				break;

			case 0x03:
				Toast.makeText(ChildTaskActivity.this, msg.getData().getString("error"), Toast.LENGTH_LONG).show();
				break;
			default:
				break;
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_childtask);
		SocoolApplication.addActivity(this);
		// mActionBarHelperBase = (ActionBarHelperBase)
		// this.getActionBarHelper();
		// mActionBarHelperBase.setmCenterViewFactory(this);
		// mActionBarHelperBase.setmSpinnerViewFactory(this);

		mContentResolver = getContentResolver();
		btn_scan = (Button) findViewById(R.id.btn_scan);
		rl_bulr = (RelativeLayout) findViewById(R.id.rl_bulr);

		taskid = this.getIntent().getStringExtra("taskid");
		subtaskid = this.getIntent().getStringExtra("subtaskid");
		taskName = getIntent().getStringExtra("taskName");

		pDialog = new ProgressDialog(this, "正在提交中");
		taskQuestionDao = new SifTaskQuestionDao(this);

		finish = (TextView) findViewById(R.id.finishButton);
		automatic = (TextView) findViewById(R.id.automaticButton);
		manual = (TextView) findViewById(R.id.manualButton);
		mark = (TextView) findViewById(R.id.MarkButton);

		btn_onechoose = (Button) findViewById(R.id.onekeychoose);

		tv_back = (TextView) findViewById(R.id.tv_back_child);
		tv_title = (TextView) findViewById(R.id.tv_title_child);
		iv_detail = (ImageView) findViewById(R.id.iv_detail_child);
		tv_detail = (TextView) findViewById(R.id.tv_detail_child);
		tv_title.setText(taskName);

		taskname = (TextView) findViewById(R.id.taskname);

		rushTaskButton = (Button) findViewById(R.id.rushTaskButton);
		btnSearch = (Button) findViewById(R.id.btnSearch);
		btnClear = (Button) findViewById(R.id.btnClear);

		alreadyAnswer = (TextView) findViewById(R.id.alreadyAnswer);
		alreadySubmit = (TextView) findViewById(R.id.alreadySubmit);
		notAnswer = (TextView) findViewById(R.id.notAnswer);

		mListView = (PullToRefreshListView) findViewById(R.id.listview);
		mChildTaskAdapter = new ChildTaskAdapter(this);
		mListView.setAdapter(mChildTaskAdapter);

		finish.setBackgroundResource(R.drawable.submitted_title_selected);
		automatic.setBackgroundResource(R.drawable.submitted_title_normal);
		manual.setBackgroundResource(R.drawable.submitted_title_normal);
		mark.setBackgroundResource(R.drawable.submitted_title_normal);

		SharedPreferences sp = getSharedPreferences("login", Context.MODE_PRIVATE);
		UserMobile = sp.getString("UserMobile", userMobile);
		// 扫描按钮
		IsFirstAnswer();
		btn_scan.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(ChildTaskActivity.this, ZBarMainActivity.class);
				startActivityForResult(intent, 0);

			}
		});

		mListView.setOnRefreshListener(new OnRefreshListener<ListView>() {
			@Override
			public void onRefresh(PullToRefreshBase<ListView> refreshView) {
				String label = DateUtils.formatDateTime(ChildTaskActivity.this, System.currentTimeMillis(),
						DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);

				refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);

				// 清空数据重新请求
				currentIndex = 0;
				getSearchData(type);
			}
		});
		mListView.setOnLastItemVisibleListener(new OnLastItemVisibleListener() {
			@Override
			public void onLastItemVisible() {
				// lastLoadingView.setVisibility(View.VISIBLE);
				currentIndex++;
				getSearchData(type);
			}
		});
		SinofaithUtil.batchAnswer = new ArrayList<HashMap<String, String>>();
		mLoadingDialog = new LoadingDialog(this);

		btnClear.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				taskname.setText("");
				getSearchData(type);
			}
		});

		taskname.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
				// if(num>0){
				// num=0;
				// return;
				// }
				// num++;

				/**
				 * 没啥用 finish.setBackgroundResource(R.drawable.
				 * submitted_title_selected); automatic
				 * .setBackgroundResource(R.drawable.submitted_title_normal);
				 * manual
				 * .setBackgroundResource(R.drawable.submitted_title_normal);
				 */

				// 清空数据重新请求
				// mChildTaskAdapter.getMdatas().clear();
				currentIndex = 0;
				// getData();
				getSearchData(type);
			}

			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {

			}

			@Override
			public void afterTextChanged(Editable arg0) {

			}
		});

		finish.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				bottomType = -1;
				// Toast.makeText(ChildTaskActivity.this, "点击了全部，筛选出所有数据",
				// Toast.LENGTH_LONG).show();
				finish.setBackgroundResource(R.drawable.submitted_title_selected);
				automatic.setBackgroundResource(R.drawable.submitted_title_normal);
				manual.setBackgroundResource(R.drawable.submitted_title_normal);
				mark.setBackgroundResource(R.drawable.submitted_title_normal);
				rushTaskButton.setVisibility(View.GONE);
				btn_onechoose.setVisibility(View.GONE);
				checkflag = false;
				mChildTaskAdapter.notifyDataSetChanged();
				type = 0;
				// 清空数据重新请求
				currentIndex = 0;
				getData();
				getSearchData(type);
				SinofaithUtil.batchAnswer = new ArrayList<HashMap<String, String>>();
			}
		});

		automatic.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				isWhole = 3;
				bottomType = -1;
				// Toast.makeText(ChildTaskActivity.this, "点击了自动，筛选出所有自动答题的数据",
				// Toast.LENGTH_LONG).show();
				finish.setBackgroundResource(R.drawable.submitted_title_normal);
				automatic.setBackgroundResource(R.drawable.submitted_title_selected);
				manual.setBackgroundResource(R.drawable.submitted_title_normal);
				mark.setBackgroundResource(R.drawable.submitted_title_normal);

				// rushTaskButton.setVisibility(View.VISIBLE);
				// if(checkflag){
				// checkflag=false;
				// // autoAnswer();
				// }else{
				// checkflag=true;
				// }
				checkflag = true;
				mChildTaskAdapter.notifyDataSetChanged();
				type = 1;
				// 清空数据重新请求
				currentIndex = 0;
				getData();
				getSearchData(type);
				SinofaithUtil.batchAnswer = new ArrayList<HashMap<String, String>>();
			}
		});

		manual.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// Toast.makeText(ChildTaskActivity.this, "点击了手动，筛选出所有手动答题的数据",
				// Toast.LENGTH_LONG).show();
				bottomType = -1;
				finish.setBackgroundResource(R.drawable.submitted_title_normal);
				automatic.setBackgroundResource(R.drawable.submitted_title_normal);
				manual.setBackgroundResource(R.drawable.submitted_title_selected);
				mark.setBackgroundResource(R.drawable.submitted_title_normal);
				rushTaskButton.setVisibility(View.GONE);
				btn_onechoose.setVisibility(View.GONE);
				checkflag = false;
				mChildTaskAdapter.notifyDataSetChanged();
				type = 2;
				// 清空数据重新请求
				currentIndex = 0;
				getData();
				getSearchData(type);
				SinofaithUtil.batchAnswer = new ArrayList<HashMap<String, String>>();
			}
		});

		// 点击标记
		mark.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				bottomType = -1;
				finish.setBackgroundResource(R.drawable.submitted_title_normal);
				automatic.setBackgroundResource(R.drawable.submitted_title_normal);
				manual.setBackgroundResource(R.drawable.submitted_title_normal);
				mark.setBackgroundResource(R.drawable.submitted_title_selected);
				rushTaskButton.setVisibility(View.GONE);
				btn_onechoose.setVisibility(View.GONE);
				currentIndex = 0;
				type = 3;
				getData();
				getSearchData(type);
				SinofaithUtil.batchAnswer = new ArrayList<HashMap<String, String>>();

			}
		});

		rushTaskButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				Log.v("qqqq", strings.size() + "");
				// if(null!=strings && strings.size()>0){
				// for(int i=0;i<strings.size();i++){
				// String[] temps=strings.get(i);
				// autoAnswer(temps[0],temps[1]);
				// }
				// mChildTaskAdapter.getMdatas().clear();
				// currentIndex = 0;
				// getData();
				// }

				if (null != SinofaithUtil.batchAnswer && SinofaithUtil.batchAnswer.size() > 0) {
					HashMap<String, String> batchMap = SinofaithUtil.batchAnswer.get(0);
					// autoAnswer(subTaskBeans.get(0).getTemplate_ID(),
					// batchMap.get("Stemp_ID"));
					Intent intent = new Intent(ChildTaskActivity.this, AnswerQuestionActivity.class);
					intent.putExtra("flag", "1");
					intent.putExtra("autoflag", "1");
					intent.putExtra("batchflag", "1");
					intent.putExtra("type", "1");
					intent.putExtra("Template_ID", subTaskBeans.get(0).getTemplate_ID());
					intent.putExtra("taskid", taskid);
					intent.putExtra("subtaskid", subtaskid);
					intent.putExtra("Stemp_ID", batchMap.get("Stemp_ID"));
					intent.putExtra("taskName", "批量补答（共" + SinofaithUtil.batchAnswer.size() + "个问卷）");
					Log.v("qqqq", "SinofaithUtil.batchAnswer.size()" + SinofaithUtil.batchAnswer.size());
					ChildTaskActivity.this.startActivity(intent);
				} else {
					Toast.makeText(ChildTaskActivity.this, "请勾选要批量答题的任务", Toast.LENGTH_LONG).show();
				}
			}
		});

		// 一键全选
		btn_onechoose.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				SinofaithUtil.batchAnswer = new ArrayList<HashMap<String, String>>();
				// 1 全选 2 不全选 3 自由
				isWhole = isWhole == 1 ? 2 : 1;
				for (QuestionAnswerBean bean : totalAnswerlist) {
					if (isWhole == 1) {
						if (!bean.getIsFinish().equals("2") && bean.getAnswerType().equals("1")) {

							HashMap<String, String> batchMap = getBatchMap(bean.getStemp_ID());
							SinofaithUtil.batchAnswer.add(batchMap);
							bean.setSelect(true);
						}
					} else if (isWhole == 2) {
						bean.setSelect(false);
					}
				}

				getSearchData(type);
			}
		});

		tv_back.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();

			}
		});
		mPopup = new TitlePopup(this);

		iv_detail.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				mPopup.show(iv_detail, popupItems);
				mPopup.setOnPoPupItemClickListener(new OnPopupItemClickListener() {

					@Override
					public void onItemClick(int position) {
						carDetail = popupItems.get(position);
						Log.i("TAG", carDetail);
						bottomType = -1;
						getSearchData(type);

					}
				});

			}
		});

		tv_detail.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				success = 0;
				sum = S.getFileNum(ChildTaskActivity.this, UserMobile, taskid, subtaskid, null);
				recursionAnswer();
			}
		});

		// 已提交
		alreadySubmit.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				finish.setBackgroundResource(R.drawable.submitted_title_selected);
				automatic.setBackgroundResource(R.drawable.submitted_title_normal);
				manual.setBackgroundResource(R.drawable.submitted_title_normal);
				mark.setBackgroundResource(R.drawable.submitted_title_normal);
				rushTaskButton.setVisibility(View.GONE);
				btn_onechoose.setVisibility(View.GONE);
				checkflag = false;
				type = 0;
				// 清空数据重新请求
				currentIndex = 0;
				bottomType = ALREADY_SUBMIT;
				carDetail = "全部";
				getSearchData(type);
				SinofaithUtil.batchAnswer = new ArrayList<HashMap<String, String>>();

			}
		});

		// 已回答
		alreadyAnswer.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				try {
					finish.setBackgroundResource(R.drawable.submitted_title_selected);
					automatic.setBackgroundResource(R.drawable.submitted_title_normal);
					manual.setBackgroundResource(R.drawable.submitted_title_normal);
					mark.setBackgroundResource(R.drawable.submitted_title_normal);
					rushTaskButton.setVisibility(View.GONE);
					btn_onechoose.setVisibility(View.GONE);
					checkflag = false;
					type = 0;
					// 清空数据重新请求
					currentIndex = 0;
					bottomType = ALREADY_ANSWER;
					carDetail = "全部";
					getSearchData(type);
					SinofaithUtil.batchAnswer = new ArrayList<HashMap<String, String>>();
				} catch (Exception ex) {
					Toast.makeText(ChildTaskActivity.this, ex.getMessage(), Toast.LENGTH_LONG).show();
				}
			}
		});
		// 未操作的
		notAnswer.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				finish.setBackgroundResource(R.drawable.submitted_title_selected);
				automatic.setBackgroundResource(R.drawable.submitted_title_normal);
				manual.setBackgroundResource(R.drawable.submitted_title_normal);
				mark.setBackgroundResource(R.drawable.submitted_title_normal);
				rushTaskButton.setVisibility(View.GONE);
				btn_onechoose.setVisibility(View.GONE);
				checkflag = false;
				type = 0;
				// 清空数据重新请求
				currentIndex = 0;
				bottomType = NOT_ANSWER;
				carDetail = "全部";
				getSearchData(type);
				SinofaithUtil.batchAnswer = new ArrayList<HashMap<String, String>>();

			}
		});
		// 获取二级分类
		SifSubTaskDao subTaskDao = new SifSubTaskDao(this);
		subTaskBeans = subTaskDao.queryBySql("select * from " + SifSubTaskBean.TABLENAME + " where Task_ID='" + taskid
				+ "' and SubTask_ID='" + subtaskid + "'");
		iteratorQuestion();
		screenDetail();
		getData();

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater menuInflater = getMenuInflater();
		menuInflater.inflate(R.menu.common, menu);
		return super.onCreateOptionsMenu(menu);
	}

	public View createView() {

		TextView tv = new TextView(this);
		tv.setText(Task_Name);
		tv.setTextColor(this.getResources().getColor(R.color.white));
		tv.setTextSize(20);
		tv.setEllipsize(TruncateAt.END);
		tv.setMaxEms(10);
		tv.setSingleLine(true);
		return tv;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) { // TODO Auto-generated
															// method stub
		if (item.getItemId() == R.id.home) {
			finish();
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	void getData() {

		SifTaskDao taskDao = new SifTaskDao(this);
		List<SifTaskBean> tasklist = taskDao
				.queryBySql("select * from " + SifTaskBean.TABLENAME + " where Task_ID='" + taskid + "'");
		Task_Name = "子任务";
		if (null != tasklist && tasklist.size() > 0) {
			taskBean = tasklist.get(0);
			Task_Name = taskBean.getTaskName();
		}
		if (null != taskName && !"".equals(taskName)) {
			Task_Name = taskName;
		}

		strings = new ArrayList<String[]>();

		SifSubTemplateDao subTemplateDao = new SifSubTemplateDao(this);
		// 获取所有三级分类
		List<SifSubTemplateBean> templateBeans = subTemplateDao
				.queryBySql("select * from " + SifSubTemplateBean.TABLENAME + " where SubTask_ID='" + subtaskid + "'");
		int total = templateBeans.size();

		answerDao = new QuestionAnswerDao(this);
		// 获取所有本地答题数据
		totalAnswerlist = answerDao.queryBySql("select * from " + QuestionAnswerBean.TABLENAME + " where Task_ID='"
				+ taskid + "' and SubTask_ID='" + subtaskid + "' and Stemp_ID in (select Stemp_ID from "
				+ SifSubTemplateBean.TABLENAME + " where SubTask_ID='" + subtaskid + "' and Task_ID='" + taskid
				+ "') and Submiter='" + UserMobile + "' group by Stemp_ID");
		Log.i("TAG", "toString----" + SinofaithUtil.userInfo.toString());
		// 已完成数量
		finishAnswerlist = answerDao.queryBySql("select * from " + QuestionAnswerBean.TABLENAME + " where Task_ID='"
				+ taskid + "' and SubTask_ID='" + subtaskid + "' and Stemp_ID in (select Stemp_ID from "
				+ SifSubTemplateBean.TABLENAME + " where SubTask_ID='" + subtaskid + "' and Task_ID='" + taskid
				+ "') and IsFinish='2' and Submiter='" + UserMobile + "' group by Stemp_ID");
		finish.setText(Html.fromHtml("全部:<font color='red'>(" + finishAnswerlist.size() + "/" + total + ")</font>"));
		// 自动答题数量
		autoAnswerlist = answerDao.queryBySql("select * from " + QuestionAnswerBean.TABLENAME + " where Task_ID='"
				+ taskid + "' and SubTask_ID='" + subtaskid + "' and Stemp_ID in (select Stemp_ID from "
				+ SifSubTemplateBean.TABLENAME + " where SubTask_ID='" + subtaskid + "' and Task_ID='" + taskid
				+ "') and AnswerType='1' and Submiter='" + UserMobile + "' group by Stemp_ID");
		automatic.setText(Html.fromHtml("自动:<font color='red'>(" + autoAnswerlist.size() + ")</font>"));
		// 手动答题
		manualAnswerlist = answerDao.queryBySql("select * from " + QuestionAnswerBean.TABLENAME + " where Task_ID='"
				+ taskid + "' and SubTask_ID='" + subtaskid + "' and Stemp_ID in (select Stemp_ID from "
				+ SifSubTemplateBean.TABLENAME + " where SubTask_ID='" + subtaskid + "' and Task_ID='" + taskid
				+ "') and AnswerType='0' and Submiter='" + UserMobile + "' group by Stemp_ID");
		manual.setText(Html.fromHtml("手动:<font color='red'>(" + manualAnswerlist.size() + ")</font>"));

		// 标记答题
		// 手动答题才会有标记

		String tempsqo = "select * from  " + SifSubTemplateBean.TABLENAME + " where IsMark='1' and Task_ID='" + taskid
				+ "' and SubTask_ID='" + subtaskid + "'";

		ArrayList<SifSubTemplateBean> queryBySqls = subTemplateDao.queryBySql(tempsqo);

		mark.setText(Html.fromHtml("标记:<font color='red'>("

				+ queryBySqls.size() + ")</font>"));

		// 获取所有标识为在库任务
		remindsList = answerDao.queryBySql("select * from " + QuestionAnswerBean.TABLENAME + " where Task_ID='" + taskid
				+ "' and SubTask_ID='" + subtaskid + "' and Submiter='" + UserMobile + "' and RemindFlag=1");
		// rushTaskButton.setVisibility(View.GONE);
		// btnSearch.setOnClickListener(new OnClickListener() {
		// @Override
		// public void onClick(View arg0) {
		// finish.setBackgroundResource(R.drawable.submitted_title_selected);
		// automatic.setBackgroundResource(R.drawable.submitted_title_normal);
		// manual.setBackgroundResource(R.drawable.submitted_title_normal);
		// // 清空数据重新请求
		// mChildTaskAdapter.getMdatas().clear();
		// currentIndex = 0;
		// getSearchData(type);
		// }
		// });

		alreadyAnswer.setText("已答: " + getAlready());

		if (SynchNoAnswer(getServerAnswer(), getNotAnswear()).size() > 0) {
			notAnswer.setText("未答: " + SynchNoAnswer(getServerAnswer(), getNotAnswear()).size());
		} else {
			notAnswer.setText("未答: " + (getAll() - getAlready() - getServerAnswer().size()));
		}

		alreadySubmit.setText("已提交: " + getAlreadySubmit());

	}

	/**
	 * 本地所有的数据
	 * 
	 * @param jSql
	 * @return
	 */
	private ArrayList<SifSubTemplateBean> getLocalAll() {

		SifSubTemplateDao subTemplateDao = new SifSubTemplateDao(ChildTaskActivity.this);
		// 获取所有三级分类
		ArrayList<SifSubTemplateBean> alls = subTemplateDao
				.queryBySql("select * from " + SifSubTemplateBean.TABLENAME + " where SubTask_ID='" + subtaskid + "'");
		return alls;

		//
		// String b = jSql.substring(0, jSql.indexOf("limit"));
		// if (b.contains("and b.IsFinish is null")) {
		// b = b.replace("and b.IsFinish is null", "");
		// }
		// Log.i("jsc", "sql:" + b);
		//
		// // 本地所有的数据
		// ArrayList<SifSubTemplateBean> siLocal = subTemplateDao.queryBySql(b);
		// Log.i("jsc", "本地所有Sql-Size():" + siLocal.size() + "");
		// return siLocal;
	}

	/**
	 * 获取从统计过来的数据(服务器的未答)
	 */
	private SynSubtaskBean getNetData() {
		String jsonNet = (String) BGSharedPreference.get(this, Utils.statistical + taskid, "");
		Log.i("jsc", "jsonNet:" + jsonNet);
		SynTaskResponse response = null;
		List<SynSubtaskBean> synSubtaskBeans = new ArrayList<SynTaskResponse.SynTaskBean.SynSubtaskBean>();
		try {
			response = HttpJsonAdapter.getInstance().get(jsonNet, SynTaskResponse.class);
		} catch (Exception e) {
			e.printStackTrace();
		}

		if (response != null && response.getResult() == 0) {
			synSubtaskBeans = response.getData().getSubtasks();
		}

		long taskidInt = 0;
		long subtaskidInt = 0;
		try {
			taskidInt = Long.valueOf(taskid);
			subtaskidInt = Long.valueOf(subtaskid);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		Log.i("jsc",
				"synSubtaskBeans:" + synSubtaskBeans.size() + "-taskid:" + taskid + "-subtaskidInt:" + subtaskidInt);
		// 当前任务服务器的未答
		SynSubtaskBean synSubtaskBeanCurrent = new SynSubtaskBean();
		for (int i = 0; i < synSubtaskBeans.size(); i++) {
			SynSubtaskBean synSubtaskBean = synSubtaskBeans.get(i);
			if (synSubtaskBean.getSubtaskid() == subtaskidInt) {
				synSubtaskBeanCurrent = synSubtaskBean;
				break;
			}
		}
		Log.i("jsc", "当前任务未完成统计的数量：" + synSubtaskBeanCurrent.getUnsubmitvinnos().size());
		return synSubtaskBeanCurrent;
	}

	/**
	 * 服务器已答 =全部 - 服务器未答 sifSubTemplateBeans 全部 synSubtaskBeans 服务器未答
	 * 
	 * @return
	 */
	private ArrayList<SifSubTemplateBean> getNetAnswered(ArrayList<SifSubTemplateBean> sifSubTemplateBeans,
			SynSubtaskBean synSubtaskBeanCurrent) {
		Log.i("jsc", "getNetAnswered-sifSubTemplateBeans:" + sifSubTemplateBeans.size() + "-SynSubtaskBean:"
				+ synSubtaskBeanCurrent.getUnsubmitvinnos().size());

		ArrayList<SifSubTemplateBean> siLocalTemp = new ArrayList<SifSubTemplateBean>();
		if (synSubtaskBeanCurrent.getUnsubmitvinnos().size() < 1) {
			return siLocalTemp;
		}
		for (int i = 0; i < sifSubTemplateBeans.size(); i++) {
			siLocalTemp.add(sifSubTemplateBeans.get(i));
		}

		for (int i = 0; i < sifSubTemplateBeans.size(); i++) {
			SifSubTemplateBean sifSubTemplateBean = sifSubTemplateBeans.get(i);
			for (int j = 0; j < synSubtaskBeanCurrent.getUnsubmitvinnos().size(); j++) {
				String unsubmitvinnoStr = synSubtaskBeanCurrent.getUnsubmitvinnos().get(j);
				if (sifSubTemplateBean.getTempNO().equals(unsubmitvinnoStr)) {
					siLocalTemp.remove(sifSubTemplateBean);
					break;
				}
			}
		}
		return siLocalTemp;
	}

	/**
	 * 得到服务器已经回答的
	 * 
	 * @return
	 */
	private ArrayList<SifSubTemplateBean> getServerAnswer() {

		ArrayList<SifSubTemplateBean> netAnswered = getNetAnswered(getLocalAll(), getNetData());
		Log.i("jsc", "服务器已答的Sql-Size():" + netAnswered.size() + "");

		return netAnswered;

	}

	void getSearchData(final int type) {

		// mLoadingDialog.show();
		// SinofaithUtil.batchAnswer = new ArrayList<HashMap<String, String>>();
		new AsyncTask<Void, Void, ArrayList<SifSubTemplateBean>>() {

			@Override
			protected ArrayList<SifSubTemplateBean> doInBackground(Void... arg0) {
				try {
					// 如果状态为0.并且没有输入.则显示遮罩层
					if (type == 0) {
						if (taskname.getText().toString().trim().equals("") && carDetail.equals("全部")
								&& bottomType == -1) {
							handler.sendEmptyMessage(0x01);
							return new ArrayList<SifSubTemplateBean>();
						}
					}

					handler.sendEmptyMessage(0x02);

					SifSubTemplateDao subTemplateDao = new SifSubTemplateDao(ChildTaskActivity.this);
					// if(null!=taskname.getText() &&
					// !"".equals(taskname.getText().toString())){
					String sql = "select a.Stemp_ID,a.SubTask_ID,a.TempNO,a.Task_ID,a.IsCare,a.IsMark,a.Detail,a.LastDate,a.Brand,a.Model,a.Color,a.FinanceDate"
							+ ",(case when b.IsFinish is null then '1.5' when b.IsFinish is not null then b.IsFinish end) as IsFinish from "
							+ SifSubTemplateBean.TABLENAME + " as a left join " + QuestionAnswerBean.TABLENAME
							+ " as b on a.Task_ID=b.Task_ID and a.SubTask_ID=b.SubTask_ID and a.Stemp_ID=b.Stemp_ID where a.SubTask_ID='"
							+ subtaskid + "' and a.TempNO like '%" + taskname.getText().toString() + "%'";
					if (type == 1) {
						// 1自动答题
						sql += " and b.AnswerType='1'";
					} else if (type == 2) {
						// 0手动答题
						sql += " and b.AnswerType='0'";
					} else if (type == 3) {
						sql += " and a.IsMark='1' ";
					}

					if (!carDetail.equals("全部")) {
						sql += " and a.Detail='" + carDetail + "'";
					}
					sql += " group by a.Stemp_ID order by IsFinish asc limit 0," + (currentIndex + 1) * 30;
					Log.v("qqqq", sql);
					Log.v("jsc", "bottomType:" + bottomType);

					if (bottomType != -1) {
						String botSql = "select * from " + QuestionAnswerBean.TABLENAME + " as a left join  "
								+ SifSubTemplateBean.TABLENAME +

								" as b on a.Task_ID=b.Task_ID and a.SubTask_ID=b.SubTask_ID and a.Stemp_ID=b.Stemp_ID  where a.Task_ID='"
								+ taskid + "' and a.SubTask_ID='" + subtaskid
								+ "' and a.Stemp_ID in (select Stemp_ID from " + SifSubTemplateBean.TABLENAME
								+ " where SubTask_ID='" + subtaskid + "'  and Task_ID='" + taskid + "' ";

						if (bottomType == ALREADY_ANSWER) {
							botSql += " and IsFinish='0' or  IsFinish='1' or IsFinish='2'  ";

						} else if (bottomType == ALREADY_SUBMIT) {
							botSql += " and IsFinish='2'";

						} else if (bottomType == NOT_ANSWER) {
							String notStr = "select a.Stemp_ID,a.SubTask_ID,a.TempNO,a.Task_ID,a.IsCare,a.IsMark,a.Detail,a.LastDate,a.Brand,a.Model,a.Color,a.FinanceDate from  "
									+ SifSubTemplateBean.TABLENAME + " as a left join  " + QuestionAnswerBean.TABLENAME
									+

									" as b on a.Task_ID=b.Task_ID and a.SubTask_ID=b.SubTask_ID and a.Stemp_ID=b.Stemp_ID  where a.Task_ID='"
									+ taskid + "' and a.SubTask_ID='" + subtaskid + "' and b.IsFinish is null and"
									+ " a.TempNO like '%" + taskname.getText().toString() + "%'"
									+ " group by a.Stemp_ID limit 0," + (currentIndex + 1) * 30;
							Log.v("qqqq", "NOT_ANSWER:" + notStr);
							// return getServerAnswer(notStr);
							ArrayList<SifSubTemplateBean> serverAnswer = getServerAnswer(); // 服务器
																							// 已答
							ArrayList<SifSubTemplateBean> queryBySql = subTemplateDao.queryBySql(notStr); // 本地未答

							if (serverAnswer.size() > 0) {
								// ArrayList<SifSubTemplateBean> queryBySqlTemp
								// = new ArrayList<SifSubTemplateBean>();
								// queryBySqlTemp.addAll((Collection<? extends
								// SifSubTemplateBean>) queryBySql.clone());
								//
								// for (int i = 0; i <queryBySqlTemp.size();
								// i++) {
								// SifSubTemplateBean sifSubTemplateBean =
								// queryBySqlTemp.get(i);
								// for (int j = 0; j < serverAnswer.size(); j++)
								// {
								// SifSubTemplateBean sifSubTemplateBeanAnswer =
								// serverAnswer.get(j);
								// if(sifSubTemplateBean.getTempNO().equals(sifSubTemplateBeanAnswer.getTempNO())){
								// queryBySqlTemp.remove(sifSubTemplateBean);
								// break;
								// }
								// }
								//
								// }
								ArrayList<SifSubTemplateBean> synchNoAnswer = SynchNoAnswer(serverAnswer, queryBySql);
								if (synchNoAnswer.size() > 0) {
									queryBySql.clear();
								}

								queryBySql.addAll(synchNoAnswer);

							}
							Log.i("jsc", "未答展示出来的数量：" + queryBySql.size());
							return queryBySql;
						}

						botSql += ") and" + " b.TempNO like '%" + taskname.getText().toString() + "%'"
								+ " and  a.Submiter='" + UserMobile
								+ "'group by a.Stemp_ID order by a.IsFinish asc limit 0," + (currentIndex + 1) * 30;
						Log.v("qqqq", botSql);
						// getServerAnswer();
						// return getServerAnswer(botSql);
						return subTemplateDao.queryBySql(botSql);
					}
					// return getServerAnswer(sql);

					return subTemplateDao.queryBySql(sql);
				} catch (Exception ex) {
					ex.printStackTrace();
					Message msg = new Message();
					msg.what = 0x03;
					Bundle b = new Bundle();
					b.putString("error", ex.getMessage());
					msg.setData(b);
					handler.sendMessage(msg);
					return new ArrayList<SifSubTemplateBean>();
				}
				// }else{
				// return null;
				// }

			}

			@Override
			protected void onPostExecute(ArrayList<SifSubTemplateBean> result) {
				// TODO Auto-generated method stub
				super.onPostExecute(result);
				Log.i("jsc", "result:" + result.size());
				mChildTaskAdapter.getMdatas().clear();

				if (null != result && result.size() > 0) {
					mChildTaskAdapter.setMdatas(result);
				}
				if (type == 1) {
					if (null == mChildTaskAdapter.getMdatas() || mChildTaskAdapter.getMdatas().size() <= 0) {
						rushTaskButton.setVisibility(View.GONE);
						btn_onechoose.setVisibility(View.GONE);
					} else {
						rushTaskButton.setVisibility(View.VISIBLE);
						btn_onechoose.setVisibility(View.VISIBLE);
					}

				}
				if (null == mChildTaskAdapter.isSelected) {
					mChildTaskAdapter.isSelected = new HashMap<Integer, Boolean>();
				}
				if (mChildTaskAdapter.isSelected.size() < mChildTaskAdapter.getMdatas().size()) {
					for (int i = 0; i < mChildTaskAdapter.getMdatas().size(); i++) {
						if (i > mChildTaskAdapter.isSelected.size() - 1) {
							mChildTaskAdapter.isSelected.put(i, false);
						}
					}
				}
				mChildTaskAdapter.notifyDataSetChanged();
				mListView.onRefreshComplete();
				// mLoadingDialog.dismiss();
			}
		}.execute();
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	private QuestionAnswerReqBean submitAnswer(final String Stemp_ID) {
		Log.v("qqqq", "stemp_id:" + Stemp_ID);
		answerReqBean = new QuestionAnswerReqBean();
		answerReqBean.setTask_ID(taskid);
		answerReqBean.setSubTask_ID(subtaskid);
		answerReqBean.setStemp_ID(Stemp_ID);
		answerReqBean.setSubmiter(UserMobile);
		SubAnswer = new ArrayList<AnswerReq>();
		// 找到答题表的数据
		answerlist = answerDao.queryBySql(
				"select * from " + QuestionAnswerBean.TABLENAME + " where Task_ID='" + taskid + "' and SubTask_ID='"
						+ subtaskid + "' and Stemp_ID='" + Stemp_ID + "' and Submiter='" + UserMobile + "'");
		SifTaskQuestionDao questionDao = new SifTaskQuestionDao(this);

		if (null != answerlist && answerlist.size() > 0) {
			for (int i = 0; i < answerlist.size(); i++) {
				QuestionAnswerBean answerBean = answerlist.get(i);
				AnswerReq answerReq = new AnswerReq();
				answerReq.setAnswer(answerBean.getAnswer());
				answerReq.setFileCount(answerBean.getFileCount());
				answerReq.setOtherAnswer(answerBean.getOtherAnswer());
				answerReq.setTaskQuestion_ID(answerBean.getTaskQuestion_ID());

				ArrayList<SifTaskQuestionBean> questionBeans = questionDao.queryBySql("select * from "
						+ SifTaskQuestionBean.TABLENAME + " where Template_ID='" + subTaskBeans.get(0).getTemplate_ID()
						+ "' and TaskQuestion_ID=" + answerBean.getTaskQuestion_ID());
				SifTaskQuestionBean taskQuestionBean = questionBeans.get(0);
				answerReq.setQuestion(taskQuestionBean.getQuestion());
				answerReq.setQuestionType(taskQuestionBean.getQuestionType());
				answerReq.setOrder(taskQuestionBean.getOrderIndex());
				answerReq.setGPS(answerBean.getGPS());
				SubAnswer.add(answerReq);
			}
		}
		// 把一个Stemplate的题目答案全部放到集合里
		answerReqBean.setSubAnswer(SubAnswer);
		try {
			if (null != answerReqBean.getSubAnswer() && answerReqBean.getSubAnswer().size() > 0) {
				for (int i = 0; i < answerReqBean.getSubAnswer().size(); i++) {
					AnswerReq answerReq = answerReqBean.getSubAnswer().get(i);
					if (null != answerReq.getFileCount() && !"".equals(answerReq.getFileCount())
							&& !"0".equals(answerReq.getFileCount())) {
						for (int j = 0; j < Integer.valueOf(answerReq.getFileCount()); j++) {
							count++;
							totalcount++;

							sum++;
						}
					}
				}
			}

			tempjson = HttpJsonAdapter.getInstance().toJson(answerReqBean);
			// Toast.makeText(this, tempjson, Toast.LENGTH_LONG).show();
			Log.v("qqqq", tempjson);
		} catch (Exception e) {
			e.printStackTrace();
		}
		end = "0";
		FinalHttp fh = new FinalHttp();
		AjaxParams params = new AjaxParams();
		params.put("sid", ConstansJsonUrl.uploadAnswer_url);
		params.put("did", SinofaithUtil.did);
		params.put("dajson", tempjson);

		if (totalcount == 0) {
			params.put("taskfinally", "1");
		}
		fh.post(ConstansJsonUrl.REQUEST_URL, params, new AjaxCallBack() {

			@Override
			public void onStart() {
				// TODO Auto-generated method stub
				super.onStart();
				mLoadingDialog.show();
			}

			@Override
			public void onLoading(long count, long current) {
				// TODO Auto-generated method stub
				super.onLoading(count, current);
			}

			@Override
			public void onSuccess(Object t) {
				// mLoadingDialog.dismiss();
				super.onSuccess(t);
				try {
					BaseMessage baseMessage = HttpJsonAdapter.getInstance().get(t.toString(), BaseMessage.class);
					if (baseMessage.getResult().equals("0")) {
						// QuestionAnswerDao answerDao = new QuestionAnswerDao(
						// ChildTaskActivity.this);
						// if (null != answerlist && answerlist.size() > 0) {
						// for (int i = 0; i < answerlist.size(); i++) {
						// QuestionAnswerBean answerBean = answerlist
						// .get(i);
						// answerBean.setIsFinish("2");
						// answerDao.update(answerBean);
						// }
						// }
						// Toast.makeText(ChildTaskActivity.this,
						// baseMessage.getDesc(), Toast.LENGTH_LONG)
						// .show();
						if (count == 0) {
							Log.i(tag, "count " + count);
							mLoadingDialog.dismiss();
							QuestionAnswerDao answerDao = new QuestionAnswerDao(ChildTaskActivity.this);
							// List<QuestionAnswerBean> answerlist = answerDao
							// .queryBySql("select * from "
							// + QuestionAnswerBean.TABLENAME
							// + " where Task_ID='" + answerBean.getTask_ID()
							// + "' and SubTask_ID='"
							// +
							// answerBean.getSubTask_ID()+"' and
							// Stemp_ID='"+answerBean.getStemp_ID()+"' and
							// Submiter='"+SinofaithUtil.userInfo.getUserMobile()+"'");

							String sql = "select * from " + QuestionAnswerBean.TABLENAME + " where Task_ID=" + taskid
									+ " and SubTask_ID=" + subtaskid;
							if (null != Stemp_ID && !"".equals(Stemp_ID)) {
								sql += " and Stemp_ID=" + Stemp_ID;
							}
							sql += " and Submiter=" + UserMobile;
							List<QuestionAnswerBean> answerlist = answerDao.queryBySql(sql);
							if (null != answerlist && answerlist.size() > 0) {
								for (int i = 0; i < answerlist.size(); i++) {
									QuestionAnswerBean answerBean = answerlist.get(i);
									answerBean.setIsFinish("2");
									answerDao.update(answerBean);
								}
							}
							Toast.makeText(ChildTaskActivity.this, "提交成功，谢谢参与！", Toast.LENGTH_LONG).show();
							// 清空数据重新请求
							currentIndex = 0;
							SinofaithUtil.batchAnswer.clear();
							getSearchData(type);
							getData();
							Log.i("TAG", "if");
						} else {
							Log.i(tag, "else");
							ArrayList<AnswerReq> answerReqs = answerReqBean.getSubAnswer();
							if (null != answerReqs && answerReqs.size() > 0) {
								Log.i("TAG", "MEI LE SHI MA");
								int begin = 0;
								for (int i = 0; i < answerReqs.size(); i++) {
									AnswerReq answerReq = answerReqs.get(i);
									if (null != answerReq.getFileCount() && !"".equals(answerReq.getFileCount())
											&& !"0".equals(answerReq.getFileCount())) {
										String[] temps = answerReq.getAnswer().split("#");
										for (int j = 0; j < Integer.valueOf(answerReq.getFileCount()); j++) {
											Log.v("qqqq", temps[j]);
											Log.i(tag, "temps+j" + temps[j]);
											if (null != temps[j] && !"".equals(temps[j])) {
												File file = new File(temps[j]);
												final String temppath = temps[j];
												String fileName = file.getName();
												String fileType = fileName.substring(fileName.lastIndexOf(".") + 1,
														fileName.length());
												if (j == (Integer.valueOf(answerReq.getFileCount()) - 1)) {
													end = "1";
												}
												String qtype = "1";
												if ("3".equals(answerReq.getQuestionType())) {
													qtype = "1";
												} else if ("4".equals(answerReq.getQuestionType())) {
													qtype = "2";
												} else {
													qtype = "3";
												}
												if (begin == 0 && count > 1) {
													firstParamsMap.put("taskid", answerReqBean.getTask_ID());
													firstParamsMap.put("subtaskid", answerReqBean.getSubTask_ID());
													firstParamsMap.put("tempid", answerReqBean.getStemp_ID());
													firstParamsMap.put("questionid", answerReq.getTaskQuestion_ID());
													firstParamsMap.put("mobile", UserMobile);
													firstParamsMap.put("ftype", qtype);
													firstParamsMap.put("suffix", fileType);
													firstParamsMap.put("order", answerReq.getOrder());
													firstParamsMap.put("desc", answerReq.getOtherAnswer());
													firstParamsMap.put("path", temppath);
													firstParamsMap.put("GPS", answerReq.getGPS());
													totalcount--;
													begin++;
													continue;
												}
												mLoadingDialog.show();
												Log.i(tag, "uploadFile");
												uploadFile(answerReqBean.getTask_ID(), answerReqBean.getSubTask_ID(),
														answerReqBean.getStemp_ID(), answerReq.getTaskQuestion_ID(),
														qtype, fileType, answerReq.getOrder(),
														answerReq.getOtherAnswer(), file, answerReq.getGPS());
											}
										}
									}
								}
							} else {
								Log.i(tag, "zhele shi ma");
							}
						}

					} else {
						Log.i(tag, "else error");
						mLoadingDialog.dismiss();
						Toast.makeText(ChildTaskActivity.this, baseMessage.getDesc(), Toast.LENGTH_LONG).show();

					}
				} catch (Exception e) {
					Log.i(tag, "catch error");
					mLoadingDialog.dismiss();
					Toast.makeText(ChildTaskActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
				}

			}

			@Override
			public void onFailure(Throwable t, int errorNo, String strMsg) {
				mLoadingDialog.dismiss();
				super.onFailure(t, errorNo, strMsg);
				Toast.makeText(ChildTaskActivity.this, strMsg, Toast.LENGTH_LONG).show();
			}

		});
		return answerReqBean;
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	void uploadFile(final String taskid, final String subtaskid, final String tempid, final String questionid,
			String ftype, String suffix, String order, String desc, File file, String GPS) {
		if (totalcount > 0) {
			totalcount--;
		}
		FinalHttp fh = new FinalHttp();
		final AjaxParams params = new AjaxParams();
		params.put("sid", ConstansJsonUrl.uploadFile_url);
		params.put("did", SinofaithUtil.did);
		params.put("taskid", taskid);
		params.put("subtaskid", subtaskid);
		params.put("tempid", tempid);
		params.put("questionid", questionid);
		params.put("mobile", UserMobile);
		params.put("ftype", ftype);
		params.put("suffix", suffix);
		params.put("order", order);
		params.put("desc", desc);
		params.put("finally", end);
		if (count == 1) {
			params.put("taskfinally", "1");
		}
		params.put("GPS", GPS);
		try {
			// upfile=file;
			// new
			// MyTask().execute(ConstansJsonUrl.REQUEST_URL+"?"+params,file.getAbsolutePath());

			S.FileParams(this, params, file);
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		Log.v("qqqq", ConstansJsonUrl.REQUEST_URL + "?" + params);
		end = "0";
		fh.post(ConstansJsonUrl.REQUEST_URL, null, params, null, new AjaxCallBack() {
			@Override
			public void onStart() {
				// TODO Auto-generated method stub
				super.onStart();
				// if(!mLoadingDialog.isShowing()){
				// mLoadingDialog.show();
				// }
			}

			@Override
			public void onLoading(long count, long current) {
				// TODO Auto-generated method stub
				super.onLoading(count, current);
			}

			@Override
			public void onSuccess(Object t) {
				super.onSuccess(t);
				try {
					BaseMessage baseMessage = HttpJsonAdapter.getInstance().get(t.toString(), BaseMessage.class);
					if (baseMessage.getResult().equals("0")) {
						// if (count > 0) {
						count--;
						success++;
						// }
						if (count == 1 && null != firstParamsMap) {
							if (null != firstParamsMap.get("path")) {
								File file = new File(firstParamsMap.get("path"));
								if (null != file && file.exists()) {
									mLoadingDialog.show();
									end = "1";
									uploadFile(firstParamsMap.get("taskid"), firstParamsMap.get("subtaskid"),
											firstParamsMap.get("tempid"), firstParamsMap.get("questionid"),
											firstParamsMap.get("ftype"), firstParamsMap.get("suffix"),
											firstParamsMap.get("order"), firstParamsMap.get("desc"), file,
											firstParamsMap.get("GPS"));
								}
							}
						}
						if (count == 0) {
							mLoadingDialog.dismiss();
							QuestionAnswerDao answerDao = new QuestionAnswerDao(ChildTaskActivity.this);
							String sql = "select * from " + QuestionAnswerBean.TABLENAME + " where Task_ID=" + taskid
									+ " and SubTask_ID=" + subtaskid;
							if (null != tempid && !"".equals(tempid)) {
								sql += " and Stemp_ID=" + tempid;
							}
							sql += " and Submiter=" + UserMobile;
							List<QuestionAnswerBean> answerlist = answerDao.queryBySql(sql);
							if (null != answerlist && answerlist.size() > 0) {
								for (int i = 0; i < answerlist.size(); i++) {
									QuestionAnswerBean answerBean = answerlist.get(i);
									answerBean.setIsFinish("2");
									answerDao.update(answerBean);
								}
							}
							// Toast.makeText(ChildTaskActivity.this,
							// "提交成功，谢谢参与！", Toast.LENGTH_LONG).show();
							showDialog(ChildTaskActivity.this, sum, success);
							currentIndex = 0;
							SinofaithUtil.batchAnswer.clear();
							getData();
							getSearchData(type);
						}
					} else {
						Log.i("TAG", "uploadfile else error");
						mLoadingDialog.dismiss();
						Log.v("error", baseMessage.getDesc());
						// Toast.makeText(ChildTaskActivity.this,
						// baseMessage.getDesc(),
						// Toast.LENGTH_LONG).show();
						paramsList.add(params);
						reUpload();
					}
				} catch (Exception e) {
					Log.i("TAG", "uploadfile catch error");
					mLoadingDialog.dismiss();
					Log.v("error", e.getMessage());
					// Toast.makeText(ChildTaskActivity.this,
					// e.getMessage(), Toast.LENGTH_LONG)
					// .show();
					paramsList.add(params);
					reUpload();
				}

			}

			@Override
			public void onFailure(Throwable t, int errorNo, String strMsg) {
				mLoadingDialog.dismiss();
				Log.i("TAG", "uploadfile  onfailed");
				super.onFailure(t, errorNo, strMsg);
				// Toast.makeText(ChildTaskActivity.this, strMsg,
				// Toast.LENGTH_LONG).show();
				paramsList.add(params);
				reUpload();
			}

		});
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	void reUpload() {
		fcount++;
		if (null != paramsList && paramsList.size() > 0) {
			mLoadingDialog.dismiss();
			if (null != dialog && dialog.isShowing()) {
				return;
			}
			MyDialog.Builder builder = new MyDialog.Builder(this);
			builder.setTitle("当前网络异常，请稍候尝试提交").setPositiveButton("确定",
					new android.content.DialogInterface.OnClickListener() {
						@Override
						public void onClick(final DialogInterface dialog111, int which) {
							// dialog.dismiss();
							// mLoadingDialog.show();
							// failcount=paramsList.size();
							// failtotalcount=paramsList.size();
							// for(int i=0;i<paramsList.size();i++){
							// final AjaxParams params=paramsList.get(i);
							// Log.v("qqqq", params+"");
							// // paramsList.remove(i);
							// // i=i-1;
							// if(null!=params){
							// if(failtotalcount>0){
							// failtotalcount--;
							// }
							// FinalHttp fh = new FinalHttp();
							// fh.post(ConstansJsonUrl.REQUEST_URL,null,
							// params,null, new AjaxCallBack() {
							// @Override
							// public void onStart() {
							// // TODO Auto-generated method stub
							// super.onStart();
							// // if(!mLoadingDialog.isShowing()){
							// mLoadingDialog.show();
							// // }
							// }
							//
							// @Override
							// public void onLoading(long count, long current) {
							// // TODO Auto-generated method stub
							// super.onLoading(count, current);
							// }
							//
							// @Override
							// public void onSuccess(Object t) {
							// super.onSuccess(t);
							// try {
							// BaseMessage baseMessage = HttpJsonAdapter
							// .getInstance().get(t.toString(),
							// BaseMessage.class);
							// if (baseMessage.getResult().equals("0")) {
							// if(failcount>0){
							// failcount--;
							// }
							// if(failcount==0){
							// mLoadingDialog.dismiss();
							// QuestionAnswerDao answerDao = new
							// QuestionAnswerDao(
							// ChildTaskActivity.this);
							// String sql = "select * from "
							// + QuestionAnswerBean.TABLENAME +
							// " where Task_ID="
							// + taskid + " and SubTask_ID=" + subtaskid;
							// if (null != answerReqBean.getStemp_ID() &&
							// !"".equals(answerReqBean.getStemp_ID())) {
							// sql += " and Stemp_ID=" +
							// answerReqBean.getStemp_ID();
							// }
							// sql += " and Submiter="
							// + SinofaithUtil.userInfo.getUserMobile();
							// List<QuestionAnswerBean> answerlist = answerDao
							// .queryBySql(sql);
							// if(null!=answerlist && answerlist.size()>0){
							// for(int i=0;i<answerlist.size();i++){
							// QuestionAnswerBean answerBean=answerlist.get(i);
							// answerBean.setIsFinish("2");
							// answerDao.update(answerBean);
							// }
							// }
							// Toast.makeText(ChildTaskActivity.this,
							// "提交成功，谢谢参与！", Toast.LENGTH_LONG).show();
							// mChildTaskAdapter.getMdatas().clear();
							// currentIndex = 0;
							// getData();
							// getSearchData();
							// }
							// lock.unlock();
							// } else {
							// mLoadingDialog.dismiss();
							// // Log.v("error", baseMessage.getDesc());
							// // Toast.makeText(ChildTaskActivity.this,
							// // baseMessage.getDesc()+"111",
							// // Toast.LENGTH_LONG).show();
							// // btnNext.setEnabled(true);
							// paramsList.add(params);
							// // if(totalcount==0){
							// // if(null==dialog || !dialog.isShowing()){
							// reUpload();
							// // }
							// // }
							// }
							// } catch (Exception e) {
							// mLoadingDialog.dismiss();
							// // Log.v("error", e.getMessage());
							// // Toast.makeText(ChildTaskActivity.this,
							// // e.getMessage()+"222", Toast.LENGTH_LONG)
							// // .show();
							// // btnNext.setEnabled(true);
							// paramsList.add(params);
							// // if(totalcount==0){
							// // if(null==dialog || !dialog.isShowing()){
							// reUpload();
							// // }
							// // }
							// }
							//
							// }
							//
							// @Override
							// public void onFailure(Throwable t, int errorNo,
							// String strMsg) {
							// mLoadingDialog.dismiss();
							// super.onFailure(t, errorNo, strMsg);
							// // Toast.makeText(ChildTaskActivity.this, strMsg,
							// // Toast.LENGTH_LONG).show();
							// // btnNext.setEnabled(true);
							// paramsList.add(params);
							// // if(totalcount==0){
							// // if(null==dialog || !dialog.isShowing()){
							// reUpload();
							// // }
							// // }
							// }
							//
							// });
							// }
							// }
							if (fcount >= 1) {
								Toast.makeText(ChildTaskActivity.this, "当前网络异常，请稍候尝试提交", Toast.LENGTH_LONG).show();
								dialog.dismiss();
								dialog = null;
							}
						}
					});
			// .setNegativeButton(
			// "取消",
			// new android.content.DialogInterface.OnClickListener() {
			//
			// @Override
			// public void onClick(
			// DialogInterface dialog,
			// int which) {
			// mLoadingDialog.dismiss();
			// dialog.dismiss();
			// dialog=null;
			// paramsList.clear();
			// lock.unlock();
			// return;
			// }
			// });
			dialog = builder.create();
			if (dialog.isShowing()) {

			} else {
				dialog.show();
			}

		}
	}

	class ChildTaskAdapter extends BaseAdapter {

		private List<SifSubTemplateBean> mdatas = new ArrayList<SifSubTemplateBean>();

		private LayoutInflater inflater;
		String[] cbs;
		private Context mContext;
		public HashMap<Integer, Boolean> isSelected;

		public List<SifSubTemplateBean> getMdatas() {
			return mdatas;
		}

		public void setMdatas(List<SifSubTemplateBean> mdatas) {
			this.mdatas = mdatas;
		}

		public void addDatas(List<SifSubTemplateBean> mdatas) {
			this.mdatas.addAll(mdatas);
			this.notifyDataSetChanged();
		}

		public ChildTaskAdapter(Context _context) {
			super();
			mContext = _context;
			inflater = LayoutInflater.from(_context);
			isSelected = new HashMap<Integer, Boolean>();
		}

		@Override
		public int getCount() {
			if (mdatas != null) {

				return mdatas.size();
			}
			return 0;
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(final int position, View convertView, ViewGroup arg2) {
			Log.i("TAG", mdatas.size() + "     mdatas.size()");
			ViewHolder mViewHolder = null;
			if (convertView == null) {
				convertView = inflater.inflate(R.layout.childtask_listitem, null);
				mViewHolder = new ViewHolder();
				mViewHolder.childtaskName = (TextView) convertView.findViewById(R.id.childtaskNameTextView);
				mViewHolder.isStoreroom = (TextView) convertView.findViewById(R.id.isStoreroom);
				mViewHolder.states = (TextView) convertView.findViewById(R.id.states);
				mViewHolder.btn_auto = (Button) convertView.findViewById(R.id.btn_auto);
				mViewHolder.btn_manual = (Button) convertView.findViewById(R.id.btn_manual);
				mViewHolder.chb_auto = (CheckBox) convertView.findViewById(R.id.chb_auto);
				mViewHolder.star = (ImageView) convertView.findViewById(R.id.star);
				mViewHolder.btn_mark = (Button) convertView.findViewById(R.id.btn_mark);
				mViewHolder.btn_take = (Button) convertView.findViewById(R.id.btn_take);
				mViewHolder.answertype = (TextView) convertView.findViewById(R.id.answertype);
				mViewHolder.tv_code = (TextView) convertView.findViewById(R.id.tv_code_childtask);
				mViewHolder.tv_brand = (TextView) convertView.findViewById(R.id.tv_brand_childtask);
				mViewHolder.tv_model = (TextView) convertView.findViewById(R.id.tv_model_childtask);
				mViewHolder.tv_color = (TextView) convertView.findViewById(R.id.tv_color_childtask);
				mViewHolder.tv_date = (TextView) convertView.findViewById(R.id.tv_date_childtask);

				mViewHolder.ll_detail_childtask = (LinearLayout) convertView.findViewById(R.id.ll_detail_childtask);
				convertView.setTag(mViewHolder);
			} else {
				mViewHolder = (ViewHolder) convertView.getTag();
			}

			if ("1".equals(mdatas.get(position).getIsCare())) {
				mViewHolder.star.setVisibility(View.VISIBLE);
			} else {
				mViewHolder.star.setVisibility(View.GONE);
			}

			if (mdatas.size() == 1) {
				mViewHolder.ll_detail_childtask.setVisibility(View.VISIBLE);
				mViewHolder.tv_code.setText(mChildTaskAdapter.getMdatas().get(0).getLastDate());
				mViewHolder.tv_brand.setText(mChildTaskAdapter.getMdatas().get(0).getBrand());
				mViewHolder.tv_color.setText(mChildTaskAdapter.getMdatas().get(0).getColor());
				mViewHolder.tv_model.setText(mChildTaskAdapter.getMdatas().get(0).getModel());
				mViewHolder.tv_date.setText(mChildTaskAdapter.getMdatas().get(0).getFinanceDate());
			} else {
				mViewHolder.ll_detail_childtask.setVisibility(View.GONE);
			}

			// 根据循环判断第一题是否为拍照

			mViewHolder.childtaskName.setText(mdatas.get(position).getTempNO());
			mViewHolder.chb_auto.setVisibility(View.GONE);

			mViewHolder.chb_auto.setChecked(false);

			convertView.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View arg0) {
					isWhole = 3;
					if (type != 1) {
						return;
					}
					HashMap<String, String> batchMap = new HashMap<String, String>();
					batchMap.put("flag", "1");
					batchMap.put("autoflag", "1");
					batchMap.put("type", "1");
					batchMap.put("Template_ID", subTaskBeans.get(0).getTemplate_ID());
					batchMap.put("taskid", taskid);
					batchMap.put("subtaskid", subtaskid);
					batchMap.put("Stemp_ID", mdatas.get(position).getStemp_ID());

					ViewHolder holder = (ViewHolder) arg0.getTag();
					holder.chb_auto.toggle();
					isSelected.put(position, holder.chb_auto.isChecked());
					if (holder.chb_auto.isChecked()) {
						Log.i("TAG", "add batchMap");
						SinofaithUtil.batchAnswer.add(batchMap);

					} else {
						Log.i("TAG", "remove batchMap");
						SinofaithUtil.batchAnswer.remove(batchMap);
					}

					for (QuestionAnswerBean bean : totalAnswerlist) {
						if (mdatas.get(position).getStemp_ID().equals(bean.getStemp_ID())) {
							bean.setSelect(holder.chb_auto.isChecked());
						}
					}

				}
			});

			// mViewHolder.chb_auto
			// .setOnCheckedChangeListener(new OnCheckedChangeListener() {
			// @Override
			// public void onCheckedChanged(CompoundButton arg0,
			// boolean arg1) {
			//
			// isSelected.put(position, arg0.isChecked());
			// }
			// });

			mViewHolder.isStoreroom.setVisibility(View.GONE);
			if (null != remindsList && remindsList.size() > 0) {
				for (int i = 0; i < remindsList.size(); i++) {
					QuestionAnswerBean answerBean = remindsList.get(i);
					if (answerBean.getStemp_ID().equals(mdatas.get(position).getStemp_ID())) {
						mViewHolder.isStoreroom.setVisibility(View.VISIBLE);
					}
				}
			}

			Log.i("TAG", totalAnswerlist.size() + "      totalAnswerList.size");
			// 有答案编辑过
			if (null != totalAnswerlist && totalAnswerlist.size() > 0) {

				boolean flag = false;
				for (int i = 0; i < totalAnswerlist.size(); i++) {
					final QuestionAnswerBean answerBean = totalAnswerlist.get(i);

					if (answerBean.getStemp_ID().equals(mdatas.get(position).getStemp_ID())) {
						// 代表有编辑过
						flag = true;
						Log.i("TAG", "if true");
						mViewHolder.btn_mark.setVisibility(View.GONE);
						mViewHolder.btn_take.setVisibility(View.GONE);

						// 未提交
						if (!answerBean.getIsFinish().equals("2")) {

							mViewHolder.childtaskName.setTextColor(mContext.getResources().getColor(R.color.nosubmit));
							mViewHolder.states.setText("未提交");

							mViewHolder.btn_auto.setText("提交");
							mViewHolder.btn_auto.setBackgroundResource(R.drawable.btn_blue);
							mViewHolder.btn_auto.setVisibility(View.VISIBLE);
							mViewHolder.btn_auto.setOnClickListener(new OnClickListener() {
								@Override
								public void onClick(View arg0) {
									if ("0".equals(answerBean.getIsFinish())) {
										Toast.makeText(ChildTaskActivity.this, "该问卷尚未回答完毕，无法提交，请继续回答后再提交",
												Toast.LENGTH_LONG).show();
										return;
									} else {
										mLoadingDialog.show();
										new Handler().postDelayed(new Runnable() {
											@Override
											public void run() {
												// TODO
												// Auto-generated
												// method stub
												// Log.i("TAG", "auto position:"
												// + position);
												// Log.i("TAG", "auto stemp_id:"
												// + mdatas
												// .get(position)
												// .getStemp_ID());
												success = 0;
												sum = 0;
												answerReqBean = submitAnswer(mdatas.get(position).getStemp_ID());
											}
										}, 1000);
									}
								}
							});

							mViewHolder.btn_manual.setBackgroundResource(R.drawable.btn_cyan);
							mViewHolder.btn_manual.setVisibility(View.VISIBLE);

							if (answerBean.getAnswerType().equals("0")) {
								// 手动答题
								mViewHolder.btn_manual.setText("修改");
								flagtemp = "1";
								mViewHolder.answertype.setText("手动答题");
								mViewHolder.answertype.setVisibility(View.VISIBLE);
							} else {
								// 如果选择了
								Log.i(tag, answerBean.isSelect() + "   isSelect");
								if (answerBean.isSelect()) {
									mViewHolder.chb_auto.setChecked(true);
								} else {
									mViewHolder.chb_auto.setChecked(false);
								}

								// 自动答题
								mViewHolder.btn_manual.setText("补答");
								flagtemp = "2";
								// rushTaskButton.setVisibility(View.VISIBLE);
								if (checkflag) {
									mViewHolder.chb_auto.setVisibility(View.VISIBLE);
								} else {
									mViewHolder.chb_auto.setVisibility(View.GONE);

								}
								mViewHolder.answertype.setText("自动答题");
								mViewHolder.answertype.setVisibility(View.VISIBLE);
							}
							mViewHolder.btn_manual.setOnClickListener(new OnClickListener() {
								@Override
								public void onClick(View arg0) {
									SinofaithUtil.batchAnswer = new ArrayList<HashMap<String, String>>();
									Intent intent = new Intent(mContext, AnswerQuestionActivity.class);
									// intent.putExtra("flag",
									// answerBean.getAnswerType().equals("0")?"1":"2");
									intent.putExtra("flag", "1");
									intent.putExtra("autoflag", "2".equals(flagtemp) ? "1" : "0");
									intent.putExtra("type", "1");
									intent.putExtra("Template_ID", subTaskBeans.get(0).getTemplate_ID());
									intent.putExtra("taskid", taskid);
									intent.putExtra("subtaskid", subtaskid);
									intent.putExtra("Stemp_ID", mdatas.get(position).getStemp_ID());
									intent.putExtra("taskName", mdatas.get(position).getTempNO());
									mContext.startActivity(intent);
								}
							});
							if (type == 3) {
								mViewHolder.chb_auto.setVisibility(View.GONE);
							}
							break;
						}

						// 已提交
						if (answerBean.getIsFinish().equals("2")) {
							if (type == 1) {

								HashMap<String, String> map = new HashMap<String, String>();
								map.put("flag", "1");
								map.put("autoflag", "1");
								map.put("type", "1");
								map.put("Template_ID", subTaskBeans.get(0).getTemplate_ID());
								map.put("taskid", taskid);
								map.put("subtaskid", subtaskid);
								map.put("Stemp_ID", mdatas.get(position).getStemp_ID());
								SinofaithUtil.batchAnswer.remove(map);
							}

							mViewHolder.childtaskName.setTextColor(Color.RED);
							if (answerBean.getAnswerType().equals("0")) {
								// 手动答题
								mViewHolder.answertype.setText("手动答题");
								mViewHolder.answertype.setVisibility(View.VISIBLE);
							} else {
								// 自动答题
								mViewHolder.answertype.setText("自动答题");
								mViewHolder.answertype.setVisibility(View.VISIBLE);
							}
							mViewHolder.states.setText("已提交");

							mViewHolder.btn_manual.setText("查看");
							mViewHolder.btn_manual.setBackgroundResource(R.drawable.btn_cyan);
							mViewHolder.btn_manual.setVisibility(View.VISIBLE);
							mViewHolder.btn_manual.setOnClickListener(new OnClickListener() {
								@Override
								public void onClick(View arg0) {
									Intent intent = new Intent(mContext, QuestionDetailActivity.class);
									answerlist = answerDao.queryBySql("select * from " + QuestionAnswerBean.TABLENAME
											+ " where Task_ID='" + taskid + "' and SubTask_ID='" + subtaskid
											+ "' and Stemp_ID='" + mdatas.get(position).getStemp_ID()
											+ "' and Submiter='" + UserMobile + "'");
									intent.putExtra("type", "1");
									intent.putExtra("answerlist", answerlist);
									intent.putExtra("taskid", taskid);
									intent.putExtra("Template_ID", subTaskBeans.get(0).getTemplate_ID());
									intent.putExtra("taskName", mdatas.get(position).getTempNO());
									mContext.startActivity(intent);
								}
							});

							mViewHolder.btn_auto.setVisibility(View.GONE);
							mViewHolder.btn_mark.setVisibility(View.GONE);
							mViewHolder.btn_take.setVisibility(View.GONE);
							break;
						}
					}
				}

				if (!flag) {
					Log.i("TAG", "if false");
					// 代表无编辑过

					mViewHolder.btn_mark.setText("标记");
					mViewHolder.btn_mark.setBackgroundResource(R.drawable.btn_orange);
					mViewHolder.btn_mark.setVisibility(View.VISIBLE);
					mViewHolder.btn_mark.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View v) {
							addToMark(mdatas.get(position).getStemp_ID());

						}
					});

					mViewHolder.btn_take.setText("拍照");
					mViewHolder.btn_take.setBackgroundResource(R.drawable.btn_red);
					mViewHolder.btn_take.setVisibility(View.VISIBLE);
					mViewHolder.btn_take.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View v) {
							takePhoto(mdatas.get(position).getStemp_ID());

						}
					});

					if (!isTake) {
						mViewHolder.btn_take.setVisibility(View.GONE);
					}
					mViewHolder.answertype.setVisibility(View.GONE);
					mViewHolder.childtaskName.setTextColor(Color.BLACK);
					mViewHolder.states.setText("未答题");
					mViewHolder.btn_auto.setText("自动");
					mViewHolder.btn_auto.setBackgroundResource(R.drawable.btn_blue);
					mViewHolder.btn_auto.setVisibility(View.VISIBLE);

					mViewHolder.btn_auto.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View arg0) {
							mLoadingDialog.show();

							new Handler().postDelayed(new Runnable() {

								@Override
								public void run() {
									// TODO Auto-generated method stub

									autoAnswer(subTaskBeans.get(0).getTemplate_ID(),
											mdatas.get(position).getStemp_ID());
								}
							}, 1000);
						}
					});
					mViewHolder.btn_manual.setText("手动");
					mViewHolder.btn_manual.setBackgroundResource(R.drawable.btn_cyan);
					mViewHolder.btn_manual.setVisibility(View.VISIBLE);
					mViewHolder.btn_manual.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View arg0) {
							try {
								SinofaithUtil.batchAnswer = new ArrayList<HashMap<String, String>>();
								Intent intent = new Intent(mContext, AnswerQuestionActivity.class);
								intent.putExtra("flag", "0");
								intent.putExtra("type", "1");
								intent.putExtra("Template_ID", subTaskBeans.get(0).getTemplate_ID());
								intent.putExtra("taskid", taskid);
								intent.putExtra("subtaskid", subtaskid);
								intent.putExtra("Stemp_ID", mdatas.get(position).getStemp_ID());
								intent.putExtra("taskName", mdatas.get(position).getTempNO());
								mContext.startActivity(intent);
							} catch (Exception ex) {
								Toast.makeText(mContext, ex.getMessage(), Toast.LENGTH_LONG).show();
							}
						}
					});

					if (type == 3 || (mdatas.get(position).getIsMark() != null
							&& mdatas.get(position).getIsMark().equals("1"))) {

						mViewHolder.childtaskName.setTextColor(Color.BLUE);
						mViewHolder.btn_mark.setVisibility(View.GONE);
						mViewHolder.btn_take.setVisibility(View.GONE);
						mViewHolder.chb_auto.setVisibility(View.GONE);
					}
				}
			}

			// 无编辑
			else {

				mViewHolder.btn_mark.setText("标记");
				mViewHolder.btn_mark.setBackgroundResource(R.drawable.btn_orange);
				mViewHolder.btn_mark.setVisibility(View.VISIBLE);
				mViewHolder.btn_mark.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						addToMark(mdatas.get(position).getStemp_ID());
					}
				});

				mViewHolder.btn_take.setText("拍照");
				mViewHolder.btn_take.setBackgroundResource(R.drawable.btn_red);
				mViewHolder.btn_take.setVisibility(View.VISIBLE);
				mViewHolder.btn_take.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						Log.i("TAG", " mdatas.get(position).getStemp_ID()    " + mdatas.get(position).getStemp_ID());
						takePhoto(mdatas.get(position).getStemp_ID());

					}
				});
				if (!isTake) {
					mViewHolder.btn_take.setVisibility(View.GONE);
				}

				mViewHolder.childtaskName.setTextColor(Color.BLACK);
				mViewHolder.states.setText("未答题");
				mViewHolder.btn_auto.setText("自动");
				mViewHolder.btn_auto.setBackgroundResource(R.drawable.btn_blue);
				mViewHolder.btn_auto.setVisibility(View.VISIBLE);
				mViewHolder.btn_auto.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View arg0) {
						mLoadingDialog.show();
						new Handler().postDelayed(new Runnable() {
							@Override
							public void run() {
								// TODO Auto-generated method stub
								autoAnswer(subTaskBeans.get(0).getTemplate_ID(), mdatas.get(position).getStemp_ID());
							}
						}, 1000);

					}
				});
				mViewHolder.btn_manual.setText("手动");
				mViewHolder.btn_manual.setBackgroundResource(R.drawable.btn_cyan);
				mViewHolder.btn_manual.setVisibility(View.VISIBLE);
				mViewHolder.btn_manual.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View arg0) {
						SinofaithUtil.batchAnswer = new ArrayList<HashMap<String, String>>();
						Intent intent = new Intent(mContext, AnswerQuestionActivity.class);
						intent.putExtra("Template_ID", subTaskBeans.get(0).getTemplate_ID());
						intent.putExtra("type", "1");
						intent.putExtra("taskid", taskid);
						intent.putExtra("subtaskid", subtaskid);
						intent.putExtra("Stemp_ID", mdatas.get(position).getStemp_ID());
						intent.putExtra("taskName", mdatas.get(position).getTempNO());
						mContext.startActivity(intent);
					}
				});
				if (type == 3
						|| (mdatas.get(position).getIsMark() != null && mdatas.get(position).getIsMark().equals("1"))) {

					mViewHolder.childtaskName.setTextColor(Color.BLUE);
					mViewHolder.btn_mark.setVisibility(View.GONE);
					mViewHolder.btn_take.setVisibility(View.GONE);
					mViewHolder.chb_auto.setVisibility(View.GONE);
				}

			}
			return convertView;

		}

		public final class ViewHolder {
			public TextView childtaskName, isStoreroom, states, answertype;
			public Button btn_auto, btn_manual;
			public CheckBox chb_auto;
			public ImageView star;
			public Button btn_mark, btn_take;
			public LinearLayout ll_detail_childtask;
			TextView tv_code, tv_brand, tv_date, tv_color, tv_model;

		}

	}

	@Override
	protected void onResume() {
		SinofaithUtil.batchAnswer.clear();
		isWhole = 3;
		getData();
		mChildTaskAdapter.isSelected = new HashMap<Integer, Boolean>();
		if (type == 1) {
			rushTaskButton.setVisibility(View.VISIBLE);
			btn_onechoose.setVisibility(View.VISIBLE);
			checkflag = true;
		} else {
			rushTaskButton.setVisibility(View.GONE);
			btn_onechoose.setVisibility(View.GONE);
			checkflag = false;
		}
		// mChildTaskAdapter.notifyDataSetChanged();
		// 清空数据重新请求
		// currentIndex = 0;

		getSearchData(type);
		super.onResume();
	}

	void autoAnswer(String Template_ID, String Stemp_ID) {
		// int a=0;
		// int b=1/a;

		// 问题类型
		SifTaskQuestionDao questionDao = new SifTaskQuestionDao(this);
		// 根据Template_ID(模版编号),Task_ID(任务编号) 查询,按照问题逻辑排序
		ArrayList<SifTaskQuestionBean> questionBeans = questionDao
				.queryBySql("select * from " + SifTaskQuestionBean.TABLENAME + " where Template_ID='" + Template_ID
						+ "' and Task_ID ='" + taskid + "' order by CAST (OrderIndex AS INTEGER)");
		boolean otherflag = false;
		Log.i("TAG", Template_ID + "--Template_ID");

		// 问题答案选项类型
		SifQuestionOptionsDao questionOptionsDao = new SifQuestionOptionsDao(this);
		// 问题结果数组
		SubAnswer = new ArrayList<AnswerReq>();

		int defaultcount = 0;
		if (null != questionBeans && questionBeans.size() > 0) {
			Log.e("questionBeans.size", questionBeans.size() + "!!!22");
			for (int i = 0; i < questionBeans.size(); i++) {
				SifTaskQuestionBean taskQuestionBean = questionBeans.get(i);
				ArrayList<SifQuestionOptionsBean> optionsBeans = null;
				if (taskQuestionBean.getQuestionType().equals("1")) {
					optionsBeans = questionOptionsDao
							.queryBySql("select * from " + SifQuestionOptionsBean.TABLENAME + " where TaskQuestion_ID='"
									+ taskQuestionBean.getTaskQuestion_ID() + "' and Task_ID ='" + taskid + "'");
				}

				if (null != optionsBeans && optionsBeans.size() > 0) {
					Log.e("optionsBeans.size", optionsBeans.size() + "!!!333");
					for (int k = 0; k < optionsBeans.size(); k++) {
						SifQuestionOptionsBean questionOptionsBean = optionsBeans.get(k);
						if (questionOptionsBean.getIsDefault().equals("1")) {
							defaultcount++;
						}
					}
				}
			}
		}
		if (defaultcount == 0) {
			Toast.makeText(ChildTaskActivity.this, "当前问卷未设置自动答案", Toast.LENGTH_LONG).show();
			mLoadingDialog.dismiss();
			return;
		}

		if (null != questionBeans && questionBeans.size() > 0) {

			for (int i = 0; i < questionBeans.size(); i++) {

				SifTaskQuestionBean taskQuestionBean = questionBeans.get(i);
				String answer = "";
				ArrayList<SifQuestionOptionsBean> optionsBeans = null;
				if (taskQuestionBean.getQuestionType().equals("1")) {
					optionsBeans = questionOptionsDao
							.queryBySql("select * from " + SifQuestionOptionsBean.TABLENAME + " where TaskQuestion_ID='"
									+ taskQuestionBean.getTaskQuestion_ID() + "' and Task_ID ='" + taskid + "'");
				}

				if (null != optionsBeans && optionsBeans.size() > 0) {
					Log.e("optionsBeans.size", optionsBeans.size() + "!!!4444");
					for (int k = 0; k < optionsBeans.size(); k++) {
						SifQuestionOptionsBean questionOptionsBean = optionsBeans.get(k);
						if (questionOptionsBean.getIsDefault().equals("1")) {
							answer = questionOptionsBean.getOptionValue();
							break;
						}
					}
				}

				// 缓存
				QuestionAnswerBean answerBean = new QuestionAnswerBean();
				if ("1".equals(taskQuestionBean.getQuestionType()) || "2".equals(taskQuestionBean.getQuestionType())) {

					AnswerReq answerReq = new AnswerReq();
					answerBean.setTask_ID(taskid);
					answerBean.setTaskQuestion_ID(taskQuestionBean.getTaskQuestion_ID());
					answerBean.setSubTask_ID(subtaskid);
					answerBean.setSubmiter(UserMobile);

					answerBean.setStemp_ID(Stemp_ID);
					answerBean.setFileCount("");
					// 单选题有其他选项
					answerBean.setAnswer(answer);
					otherflag = false;
					answerBean.setAnswerType("1");
					answerBean.setIsFinish("1");
					answerReq.setFileCount("");
					answerReq.setAnswer(answer);
					answerReq.setTaskQuestion_ID(taskQuestionBean.getTaskQuestion_ID());
					answerBean.setModifyTime(taskQuestionBean.getOrderIndex());
					if (null != optionsBeans && optionsBeans.size() > 0) {
						for (int k = 0; k < optionsBeans.size(); k++) {
							SifQuestionOptionsBean questionOptionsBean = optionsBeans.get(k);
							if (answer.equals(questionOptionsBean.getOptionValue())) {
								answerBean.setRemindFlag(questionOptionsBean.getRemindFlag());
							}
						}
					}
					SubAnswer.add(answerReq);

					// 好像是保存第一题的结果当作第一题已经答了
					answerDao.insert(answerBean);

				} else {
					if (taskQuestionBean.getIsRequired().equals("0")) {
						AnswerReq answerReq = new AnswerReq();
						answerBean.setTask_ID(taskid);
						answerBean.setTaskQuestion_ID(taskQuestionBean.getTaskQuestion_ID());
						answerBean.setSubTask_ID(subtaskid);
						answerBean.setSubmiter(UserMobile);

						answerBean.setStemp_ID(Stemp_ID);
						answerBean.setFileCount("");
						answerReq.setFileCount("");
						// 单选题有其他选项
						answerBean.setAnswer("");
						answerReq.setAnswer("");
						otherflag = false;
						answerBean.setAnswerType("1");
						answerBean.setIsFinish("1");
						answerReq.setTaskQuestion_ID(taskQuestionBean.getTaskQuestion_ID());
						answerBean.setModifyTime(taskQuestionBean.getOrderIndex());
						SubAnswer.add(answerReq);

						// 检测本地是否已答,并执行增加/更新操作

						answerDao.insert(answerBean);

					}
				}

			}
		}
		if (isFirstDo) {
			changeTaskFirstModifyTime();
			isFirstDo = false;
		}
		mLoadingDialog.dismiss();
		getData();
		getSearchData(type);
	}

	/**
	 * 加入到标记界面
	 */
	private void addToMark(String Stemp_ID) {

		String querysql = "select * from " + SifSubTemplateBean.TABLENAME + " where Stemp_ID ='" + Stemp_ID
				+ "' and Task_ID ='" + taskid + "'";
		SifSubTemplateDao c = new SifSubTemplateDao(this);

		ArrayList<SifSubTemplateBean> queryBySqls = c.queryBySql(querysql);

		Log.i(tag, "queryBySqls.size()" + queryBySqls.size());
		if (queryBySqls != null && queryBySqls.size() > 0) {
			SifSubTemplateBean sifSubTemplateBean = queryBySqls.get(0);
			sifSubTemplateBean.setIsMark("1");
			c.update(sifSubTemplateBean);
		}
		getData();
		getSearchData(type);

	}

	@Override
	protected void onActivityResult(int arg0, int arg1, Intent arg2) {
		// TODO Auto-generated method stub
		super.onActivityResult(arg0, arg1, arg2);
		Log.i("TAG", "onActivityResult " + arg1);
		Log.i(tag, SinofaithUtil.userInfo.toString());
		if (arg1 == 1) {
			if (arg2.getStringExtra("code") != null) {
				String code = arg2.getStringExtra("code");

				if (!Character.isDigit(code.charAt(code.length() - 1))) {
					code = code.substring(0, code.length() - 1);

				}
				if (code.length() > 17) {
					code = code.substring(0, 17);
				}
				taskname.setText(code);
			}
		}
		if (arg1 == 200) {

			if (null != arg2.getStringExtra(UseCameraActivity.IMAGE_PATH)) {
				String path = arg2.getStringExtra(UseCameraActivity.IMAGE_PATH);
				Log.i("abc", path);
				if (path == null) {
					Toast.makeText(this, "拍摄失败,请重新拍照", Toast.LENGTH_LONG).show();
				} else {
					try {
						String[] paths = path.split("#");
						for (int i = 0; i < paths.length; i++) {
							Log.i("TAG", paths[i]);
							getBitmap(paths[i]);
						}
						Log.i("jsc", "path:" + path + "-paths.length:" + paths.length);
						// 添加进答案里
						updatePhote(path, paths.length + "");
					} catch (Exception e) {
						Toast.makeText(this, "无法获取拍摄后文件,请重新拍照", Toast.LENGTH_LONG).show();
					}
				}

			} else {
				Toast.makeText(this, "无法获取拍摄后文件", Toast.LENGTH_LONG).show();
			}
		}
	}

	/**
	 * 本地未答
	 */
	private ArrayList<SifSubTemplateBean> getNotAnswear() {
		String notStr = "select a.Stemp_ID,a.SubTask_ID,a.TempNO,a.Task_ID,a.IsCare,a.IsMark,a.Detail,a.LastDate,a.Brand,a.Model,a.Color,a.FinanceDate from  "
				+ SifSubTemplateBean.TABLENAME + " as a left join  " + QuestionAnswerBean.TABLENAME +

				" as b on a.Task_ID=b.Task_ID and a.SubTask_ID=b.SubTask_ID and a.Stemp_ID=b.Stemp_ID  where a.Task_ID='"
				+ taskid + "' and a.SubTask_ID='" + subtaskid + "' and b.IsFinish is null and" + " a.TempNO like '%"
				+ taskname.getText().toString() + "%'" + " group by a.Stemp_ID ";
		SifSubTemplateDao subTemplateDao = new SifSubTemplateDao(ChildTaskActivity.this);
		ArrayList<SifSubTemplateBean> queryBySql = subTemplateDao.queryBySql(notStr);
		Log.i("jsc", "本地未答getNotAnswear():" + queryBySql.size());
		return queryBySql;
	}

	/**
	 * 同步后的未答 = 本地未答-服务器已答
	 * 
	 * @param serverAnswer
	 *            服务器已答
	 * @param queryBySql
	 *            本地
	 */
	private ArrayList<SifSubTemplateBean> SynchNoAnswer(ArrayList<SifSubTemplateBean> serverAnswer,
			ArrayList<SifSubTemplateBean> queryBySql) {
		Log.i("jsc", "SynchNoAnswer-本地未答:" + queryBySql.size() + "-服务器已答：" + serverAnswer.size());
		ArrayList<SifSubTemplateBean> queryBySqlTemp = new ArrayList<SifSubTemplateBean>();
		if (serverAnswer.size() > 0) {

			queryBySqlTemp.addAll((Collection<? extends SifSubTemplateBean>) queryBySql.clone());

			for (int i = 0; i < queryBySql.size(); i++) {
				SifSubTemplateBean sifSubTemplateBean = queryBySql.get(i);
				for (int j = 0; j < serverAnswer.size(); j++) {
					SifSubTemplateBean sifSubTemplateBeanAnswer = serverAnswer.get(j);
					if (sifSubTemplateBean.getTempNO().equals(sifSubTemplateBeanAnswer.getTempNO())) {
						queryBySqlTemp.remove(sifSubTemplateBean);
						break;
					}
				}

			}

			// sifSubTemplateBeans.addAll(queryBySqlTemp);

		}
		Log.i("jsc", "同步后的未答数量:" + queryBySqlTemp.size());
		return queryBySqlTemp;
	}

	// 已答
	private int getAlready() {

		ArrayList<QuestionAnswerBean> autos = answerDao
				.queryBySql("select * from " + QuestionAnswerBean.TABLENAME + " where Task_ID='" + taskid
						+ "' and SubTask_ID='" + subtaskid + "' and Stemp_ID in (select Stemp_ID from "
						+ SifSubTemplateBean.TABLENAME + " where SubTask_ID='" + subtaskid + "' and Task_ID='" + taskid
						+ "') and AnswerType='1' and Submiter='" + UserMobile + "' group by Stemp_ID");

		// "select * from"+ QuestionAnswerBean.TABLENAME
		// +"where Task_ID='"+taskid+"'and ";

		// 获得手动题目数量
		ArrayList<QuestionAnswerBean> manuals = answerDao
				.queryBySql("select * from " + QuestionAnswerBean.TABLENAME + " where Task_ID='" + taskid
						+ "' and SubTask_ID='" + subtaskid + "' and Stemp_ID in (select Stemp_ID from "
						+ SifSubTemplateBean.TABLENAME + " where SubTask_ID='" + subtaskid + "' and Task_ID='" + taskid
						+ "') and AnswerType='0' and Submiter='" + UserMobile + "' group by Stemp_ID");

		Log.i("jsc", "autos:" + autos.toString() + "-manuals:" + manuals.toString());
		return autos.size() + manuals.size();
	}

	// 获得已提交题目数量
	private int getAlreadySubmit() {
		ArrayList<QuestionAnswerBean> autos = answerDao.queryBySql(
				"select * from " + QuestionAnswerBean.TABLENAME + " where Task_ID='" + taskid + "' and SubTask_ID='"
						+ subtaskid + "' and Stemp_ID in (select Stemp_ID from " + SifSubTemplateBean.TABLENAME
						+ " where SubTask_ID='" + subtaskid + "' and  IsFinish='2' and Task_ID='" + taskid
						+ "') and Submiter='" + UserMobile + "' group by Stemp_ID");
		return autos.size();
	}

	// 获得所有的题目数量
	private int getAll() {
		SifSubTemplateDao subTemplateDao = new SifSubTemplateDao(this);
		// 获取所有三级分类
		List<SifSubTemplateBean> alls = subTemplateDao
				.queryBySql("select * from " + SifSubTemplateBean.TABLENAME + " where SubTask_ID='" + subtaskid + "'");
		return alls.size();
	}

	// 遍历.拍照题
	private void iteratorQuestion() {
		String tempsql = "select * from " + SifTaskQuestionBean.TABLENAME + " where Template_ID='"
				+ subTaskBeans.get(0).getTemplate_ID() + "' and Task_ID='" + taskid + "'"
				+ " order by cast(OrderIndex as INTEGER)";

		SifTaskQuestionDao taskQuestionDao = new SifTaskQuestionDao(this);
		ArrayList<SifTaskQuestionBean> questionBeans = taskQuestionDao.queryBySql(tempsql);

		boolean first = false;
		boolean second = false;
		if (questionBeans != null && questionBeans.size() > 0) {
			for (int i = 0; i < questionBeans.size(); i++) {
				// if (!first) {
				SifTaskQuestionBean bean = questionBeans.get(i);
				Log.i("jsc2", "iteratorQuestion-标题：" + bean.getQuestion());
				if (bean.getQuestion().equals("请拍车架号照片")) {
					isSpecialFlag = true;
				}
				;
				if (bean.getQuestionType().equals("3") & isAutoTake()) {
					if (!first) { // 第一个拍照
						first = true;
						questionIndex = bean.getTaskQuestion_ID();
						isTake = true;//
					} else { // 第二个拍照
						if (!second) {
							second = true;
							secondQuestionIndex = bean.getTaskQuestion_ID();
						}

					}

				}

				// }

			}

		}

		Log.i("jsc", "第一拍照ID：" + questionIndex + "第二拍照ID：" + secondQuestionIndex);

		// if (questionBeans != null && questionBeans.size() > 0
		// && questionBeans.get(0).getQuestionType().equals("3")) {
		// questionIndex = questionBeans.get(0).getTaskQuestion_ID();
		//
		// if(isAutoTake()){
		// isTake=true;
		// }else{
		// isTake = false;
		//
		// }
		//
		//
		//
		// } else {
		// isTake = false;
		// }
	}

	// 拍照片按钮
	private void takePhoto(String stempId) {
		StempIndex = stempId;
		Intent intent = new Intent(this, UseMoreCameraActivity.class);
		startActivityForResult(intent, 1);
	}

	// 更新题目作为已操作,作为自动
	private void updatePhote(String path, String fileCount) {
		Log.i("jsc", "updatePhote"+isSpecialFlag);
		if (!isSpecialFlag) {
			QuestionAnswerBean qbean = new QuestionAnswerBean();
			qbean.setAnswer(path);
			qbean.setAnswerType("1");
			qbean.setCreateTime("");
			qbean.setFileCount(fileCount);
			qbean.setFormto("");
			qbean.setGPS(SinofaithUtil.GPS);
			qbean.setIsFinish("1");
			qbean.setModifyTime("1");
			qbean.setOtherAnswer("");
			qbean.setRemindFlag("0");
			qbean.setStemp_ID(StempIndex);
			qbean.setSubmiter(UserMobile);
			qbean.setSubTask_ID(subtaskid);
			qbean.setTask_ID(taskid);
			qbean.setTaskQuestion_ID(questionIndex);
			answerDao.insert(qbean);
		} else {
			String firstPath = "";
			String secondPath = "";
	
			if (path.contains("#")) {
				try {
					// 第一张图的
					firstPath = path.subSequence(0, path.indexOf("#") + 1).toString();
					// 第二张图的
					secondPath = path.substring(path.indexOf("#") + 1, path.length());

				} catch (Exception e) {
					e.printStackTrace();
				}
			}else{
				firstPath = path;
			}

			for (int i = 0; i < 2; i++) {
				QuestionAnswerBean qbean = new QuestionAnswerBean();

				qbean.setAnswerType("1");
				qbean.setCreateTime("");
				qbean.setFormto("");
				qbean.setGPS(SinofaithUtil.GPS);
				qbean.setIsFinish("1");
				qbean.setModifyTime("1");
				qbean.setOtherAnswer("");
				qbean.setRemindFlag("0");
				qbean.setStemp_ID(StempIndex);
				qbean.setSubmiter(UserMobile);
				qbean.setSubTask_ID(subtaskid);
				qbean.setTask_ID(taskid);
				if (i == 0) {
					qbean.setTaskQuestion_ID(questionIndex);
					qbean.setAnswer(firstPath);
					qbean.setFileCount(firstPath.split("#").length + "");
				} else if (i == 1) {
					qbean.setFileCount(secondPath.split("#").length + "");
					qbean.setAnswer(secondPath);
					qbean.setTaskQuestion_ID(secondQuestionIndex);
				}

				answerDao.insert(qbean);
			}

		}
		String Template_ID = subTaskBeans.get(0).getTemplate_ID();
		String Stemp_ID = StempIndex;
		SifTaskQuestionDao questionDao = new SifTaskQuestionDao(this);
		// 根据Template_ID(模版编号),Task_ID(任务编号) 查询,按照问题逻辑排序
		ArrayList<SifTaskQuestionBean> questionBeans = questionDao
				.queryBySql("select * from " + SifTaskQuestionBean.TABLENAME + " where Template_ID='" + Template_ID
						+ "' and Task_ID ='" + taskid + "' order by CAST (OrderIndex AS INTEGER)");
		boolean otherflag = false;
		Log.i("TAG", Template_ID + "--Template_ID");

		// 问题答案选项类型
		SifQuestionOptionsDao questionOptionsDao = new SifQuestionOptionsDao(this);
		// 问题结果数组
		SubAnswer = new ArrayList<AnswerReq>();

		int defaultcount = 0;
		if (null != questionBeans && questionBeans.size() > 0) {
			Log.e("questionBeans.size", questionBeans.size() + "!!!22");
			for (int i = 0; i < questionBeans.size(); i++) {
				SifTaskQuestionBean taskQuestionBean = questionBeans.get(i);
				ArrayList<SifQuestionOptionsBean> optionsBeans = null;
				if (taskQuestionBean.getQuestionType().equals("1")) {
					optionsBeans = questionOptionsDao
							.queryBySql("select * from " + SifQuestionOptionsBean.TABLENAME + " where TaskQuestion_ID='"
									+ taskQuestionBean.getTaskQuestion_ID() + "' and Task_ID ='" + taskid + "'");
				}

				if (null != optionsBeans && optionsBeans.size() > 0) {
					Log.e("optionsBeans.size", optionsBeans.size() + "!!!333");
					for (int k = 0; k < optionsBeans.size(); k++) {
						SifQuestionOptionsBean questionOptionsBean = optionsBeans.get(k);
						if (questionOptionsBean.getIsDefault().equals("1")) {
							defaultcount++;
						}
					}
				}
			}
		}
		if (null != questionBeans && questionBeans.size() > 0) {

			for (int i = 0; i < questionBeans.size(); i++) {

				SifTaskQuestionBean taskQuestionBean = questionBeans.get(i);
				if (taskQuestionBean.getTaskQuestion_ID().equals(questionIndex)||taskQuestionBean.getTaskQuestion_ID().equals(secondQuestionIndex)) {
					continue;
				}
				String answer = "";
				ArrayList<SifQuestionOptionsBean> optionsBeans = null;
				if (taskQuestionBean.getQuestionType().equals("1")) {
					optionsBeans = questionOptionsDao
							.queryBySql("select * from " + SifQuestionOptionsBean.TABLENAME + " where TaskQuestion_ID='"
									+ taskQuestionBean.getTaskQuestion_ID() + "' and Task_ID ='" + taskid + "'");
				}

				if (null != optionsBeans && optionsBeans.size() > 0) {
					Log.e("optionsBeans.size", optionsBeans.size() + "!!!4444");
					for (int k = 0; k < optionsBeans.size(); k++) {
						SifQuestionOptionsBean questionOptionsBean = optionsBeans.get(k);
						if (questionOptionsBean.getIsDefault().equals("1")) {
							answer = questionOptionsBean.getOptionValue();
							break;
						}
					}
				}
				Log.i("jsc", "更新" + taskQuestionBean.toString());
				// 缓存
				QuestionAnswerBean answerBean = new QuestionAnswerBean();
				if ("1".equals(taskQuestionBean.getQuestionType()) || "2".equals(taskQuestionBean.getQuestionType())) {

					AnswerReq answerReq = new AnswerReq();
					answerBean.setTask_ID(taskid);
					answerBean.setTaskQuestion_ID(taskQuestionBean.getTaskQuestion_ID());
					answerBean.setSubTask_ID(subtaskid);
					answerBean.setSubmiter(UserMobile);

					answerBean.setStemp_ID(Stemp_ID);
					answerBean.setFileCount("");
					// 单选题有其他选项
					answerBean.setAnswer(answer);
					otherflag = false;
					answerBean.setAnswerType("1");
					answerBean.setIsFinish("1");
					answerReq.setFileCount("");
					answerReq.setAnswer(answer);
					answerReq.setTaskQuestion_ID(taskQuestionBean.getTaskQuestion_ID());
					answerBean.setModifyTime(taskQuestionBean.getOrderIndex());
					if (null != optionsBeans && optionsBeans.size() > 0) {
						for (int k = 0; k < optionsBeans.size(); k++) {
							SifQuestionOptionsBean questionOptionsBean = optionsBeans.get(k);
							if (answer.equals(questionOptionsBean.getOptionValue())) {
								answerBean.setRemindFlag(questionOptionsBean.getRemindFlag());
							}
						}
					}
					SubAnswer.add(answerReq);

					// 好像是保存第一题的结果当作第一题已经答了
					answerDao.insert(answerBean);

				} else {

					if (taskQuestionBean.getIsRequired().equals("0")) {
						AnswerReq answerReq = new AnswerReq();
						answerBean.setTask_ID(taskid);
						answerBean.setTaskQuestion_ID(taskQuestionBean.getTaskQuestion_ID());
						answerBean.setSubTask_ID(subtaskid);
						answerBean.setSubmiter(UserMobile);

						answerBean.setStemp_ID(Stemp_ID);
						answerBean.setFileCount("");
						answerReq.setFileCount("");
						// 单选题有其他选项
						answerBean.setAnswer("");
						answerReq.setAnswer("");
						otherflag = false;
						answerBean.setAnswerType("1");
						answerBean.setIsFinish("1");
						answerReq.setTaskQuestion_ID(taskQuestionBean.getTaskQuestion_ID());
						answerBean.setModifyTime(taskQuestionBean.getOrderIndex());
						SubAnswer.add(answerReq);

						// 检测本地是否已答,并执行增加/更新操作

						answerDao.insert(answerBean);

					}
				}

			}
		}
		if (isFirstDo) {
			changeTaskFirstModifyTime();
			isFirstDo = false;
		}
		mLoadingDialog.dismiss();
		currentIndex = 0;
		getData();
		getSearchData(type);
	}

	private void screenDetail() {
		String sql = "select a.Stemp_ID,a.SubTask_ID,a.TempNO,a.Task_ID,a.IsCare,a.IsMark,a.Detail,a.LastDate,a.Color,a.Model,a.Brand,a.FinanceDate,"
				+ "(case when b.IsFinish is null then '1.5' when b.IsFinish is not null then b.IsFinish end) as IsFinish from "
				+ SifSubTemplateBean.TABLENAME + " as a left join " + QuestionAnswerBean.TABLENAME
				+ " as b on a.Task_ID=b.Task_ID and a.SubTask_ID=b.SubTask_ID and a.Stemp_ID=b.Stemp_ID where a.SubTask_ID='"
				+ subtaskid + "'group by a.Stemp_ID order by IsFinish asc ";

		SifSubTemplateDao subTemplateDao = new SifSubTemplateDao(ChildTaskActivity.this);
		ArrayList<SifSubTemplateBean> screenDetails = subTemplateDao.queryBySql(sql);
		String itemStr = "#";
		for (SifSubTemplateBean bean : screenDetails) {
			if (bean.getDetail() != null) {
				if (itemStr.indexOf("#" + bean.getDetail() + "#") == -1) {
					itemStr = itemStr + bean.getDetail() + "#";
				}
			}

		}
		String[] items = itemStr.split("#");
		popupItems = new ArrayList<String>();
		popupItems.add("全部");
		for (int i = 1; i < items.length; i++) {

			popupItems.add(items[i]);
		}
	}

	private boolean isAutoTake() {
		// int a=0;
		// int b=1/a;

		String Template_ID = subTaskBeans.get(0).getTemplate_ID();
		// 问题类型
		SifTaskQuestionDao questionDao = new SifTaskQuestionDao(this);
		// 根据Template_ID(模版编号),Task_ID(任务编号) 查询,按照问题逻辑排序
		ArrayList<SifTaskQuestionBean> questionBeans = questionDao
				.queryBySql("select * from " + SifTaskQuestionBean.TABLENAME + " where Template_ID='" + Template_ID
						+ "' and Task_ID ='" + taskid + "' order by CAST (OrderIndex AS INTEGER)");

		// 问题答案选项类型
		SifQuestionOptionsDao questionOptionsDao = new SifQuestionOptionsDao(this);
		// 问题结果数组
		SubAnswer = new ArrayList<AnswerReq>();

		int defaultcount = 0;
		if (null != questionBeans && questionBeans.size() > 0) {
			Log.e("questionBeans.size", questionBeans.size() + "!!!22");
			for (int i = 0; i < questionBeans.size(); i++) {
				SifTaskQuestionBean taskQuestionBean = questionBeans.get(i);
				ArrayList<SifQuestionOptionsBean> optionsBeans = null;
				if (taskQuestionBean.getQuestionType().equals("1")) {
					optionsBeans = questionOptionsDao
							.queryBySql("select * from " + SifQuestionOptionsBean.TABLENAME + " where TaskQuestion_ID='"
									+ taskQuestionBean.getTaskQuestion_ID() + "' and Task_ID ='" + taskid + "'");
				}

				if (null != optionsBeans && optionsBeans.size() > 0) {
					Log.e("optionsBeans.size", optionsBeans.size() + "!!!333");
					for (int k = 0; k < optionsBeans.size(); k++) {
						SifQuestionOptionsBean questionOptionsBean = optionsBeans.get(k);
						if (questionOptionsBean.getIsDefault().equals("1")) {
							defaultcount++;
						}
					}
				}
			}
		}
		if (defaultcount == 0) {
			return false;
		}
		return true;

	}

	private HashMap<String, String> getBatchMap(String stemp_ID) {
		HashMap<String, String> batchMap = new HashMap<String, String>();
		batchMap.put("flag", "1");
		batchMap.put("autoflag", "1");
		batchMap.put("type", "1");
		batchMap.put("Template_ID", subTaskBeans.get(0).getTemplate_ID());
		batchMap.put("taskid", taskid);
		batchMap.put("subtaskid", subtaskid);
		batchMap.put("Stemp_ID", stemp_ID);
		return batchMap;
	}

	private Uri getImageUri(String path) {
		return Uri.fromFile(new File(path));
	}

	private Bitmap getBitmap(String path) {
		Uri uri = getImageUri(path);
		InputStream is = null;
		try {

			is = mContentResolver.openInputStream(uri);
			BitmapFactory.Options o = new BitmapFactory.Options();
			// 设置成了true,不占用内存，只获取bitmap宽高
			o.inJustDecodeBounds = true;
			// 读取图片长宽
			BitmapFactory.decodeStream(is, null, o);
			is.close();

			int scale = 1;

			if (o.outHeight > IMAGE_MAX_SIZE || o.outWidth > IMAGE_MAX_SIZE) {
				scale = (int) Math.pow(2, (int) Math
						.round(Math.log(IMAGE_MAX_SIZE / (double) Math.max(o.outHeight, o.outWidth)) / Math.log(0.5)));
			}
			BitmapFactory.Options o2 = new BitmapFactory.Options();

			o2.inSampleSize = scale;
			is = mContentResolver.openInputStream(uri);
			Bitmap b = BitmapFactory.decodeStream(is, null, o2);
			if (null != b) {
				if (null != taskBean && !"".equals(taskBean.getPhotoCompression())) {
					if ("1".equals(taskBean.getPhotoCompression())) {
						b = comp(b, 1280f, 720f, path);
					} else if ("2".equals(taskBean.getPhotoCompression())) {
						b = comp(b, 1920f, 1080f, path);
					} else {
						b = comp(b, 3000f, 2000f, path);
					}
				} else {
					b = comp(b, 3000f, 2000f, path);
				}
			} else {
				Toast.makeText(ChildTaskActivity.this, "图片已损坏", 1).show();
			}
			is.close();
			return b;
		} catch (Exception e) {

		}

		return null;
	}

	// 压缩图片分辨率
	private Bitmap comp(Bitmap image, float hh, float ww, String path) {

		hh = hh + 200;// 给一定的富裕防止图片被压缩过小
		ByteArrayOutputStream baos = new ByteArrayOutputStream();

		image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
		// 判断如果图片大于1m,进行压缩,避免在生成图片（BitmapFactory.decodeStream）时溢出
		if (baos.toByteArray().length / 1024 > 1024) {
			baos.reset(); // 重置baos即清空baos
			// 压缩50% .把压缩后的数据放到baos中
			image.compress(Bitmap.CompressFormat.JPEG, 50, baos);
		}
		ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());

		BitmapFactory.Options newOpts = new BitmapFactory.Options();
		// 开始读入图片,此时把opteions.inJustDecodeBounds 设true;

		newOpts.inJustDecodeBounds = true;
		Bitmap bitmap = BitmapFactory.decodeStream(bais, null, newOpts);
		int w = newOpts.outWidth;
		int h = newOpts.outHeight;

		int be = 1;// be =1 表示不缩放
		if (w > hh || h > hh) {
			be = 2;
			while (w / be > hh || h / be > hh) {
				be = be + 2;
			}
		}
		newOpts.inSampleSize = be;// 设置缩放比例
		newOpts.inJustDecodeBounds = false;
		// 重新读入图片,
		bais = new ByteArrayInputStream(baos.toByteArray());
		bitmap = BitmapFactory.decodeStream(bais, null, newOpts);
		return compressImage(image, path);

	}

	// 图片质量压缩
	private Bitmap compressImage(Bitmap image, String path) {

		File f = new File(path);
		if (f.exists()) {
			f.delete();
		}
		try {
			FileOutputStream out = new FileOutputStream(f);
			image.compress(Bitmap.CompressFormat.JPEG, 90, out);
			out.flush();
			out.close();
		} catch (Exception e) {

		}

		return image;
	}

	private String getSPString() {
		SharedPreferences sp = this.getSharedPreferences("login", Context.MODE_PRIVATE);
		return sp.getString("UserMobile", "");
	}

	private void IsFirstAnswer() {
		QuestionAnswerDao dao = new QuestionAnswerDao(this);
		ArrayList<QuestionAnswerBean> arrayList = dao.query(taskid);
		System.out.println(arrayList.size());
		if (arrayList.size() == 0) {
			Log.i("TAG", "是不是第一次");
			isFirstDo = true;
		}
	}

	private void changeTaskFirstModifyTime() {
		Log.i("TAG", "changele mei");
		String data = com.socool.sinofaith.util.DateUtils.getStringDate();
		SifTaskDao dao = new SifTaskDao(this);
		ArrayList<SifTaskBean> arrayList = dao.query(taskid);
		for (SifTaskBean bean : arrayList) {
			bean.setModifyTime(data);
			dao.update(bean);
		}

	}

	int qCount;
	int success;
	int sum;
	private ProgressDialog pDialog;
	private String userMobile;
	private SifTaskQuestionDao taskQuestionDao;
	private ArrayList<QuestionAnswerBean> answerList;

	private void recursionAnswer() {
		userMobile = getSPString();
		String searchAnswerSql = "select * from " + QuestionAnswerBean.TABLENAME + " as answer join "
				+ SifTaskQuestionBean.TABLENAME + " as question on answer.Task_ID=question.Task_ID  and"
				+ " answer.TaskQuestion_ID=question.TaskQuestion_ID " + "where answer.SubTask_ID='" + subtaskid
				+ "' and Stemp_ID in (select Stemp_ID from " + SifSubTemplateBean.TABLENAME + " where SubTask_ID='"
				+ subtaskid + "') and Submiter='" + userMobile + "' and answer.IsFinish='1'  group by answer.Stemp_ID";

		qCount = 0;
		answerList = answerDao.queryBySql(searchAnswerSql);
		pDialog.show();
		if (answerList != null && answerList.size() > 0) {
			final QuestionAnswerBean bean = answerList.get(0);

			new Thread(new Runnable() {
				@Override
				public void run() {
					submit(bean);
				}
			}).start();
		} else {
			pDialog.dismiss();
		}
	}

	private ArrayList<UpLoadFileBean> upInfos;

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public void submit(final QuestionAnswerBean bean) {
		upInfos = new ArrayList<UpLoadFileBean>();
		final String subTaskID = bean.getSubTask_ID();
		final String stempID = bean.getStemp_ID();
		final QuestionAnswerReqBean answerReqBean = new QuestionAnswerReqBean();
		answerReqBean.setTask_ID(taskid);
		answerReqBean.setSubmiter(userMobile);
		answerReqBean.setStemp_ID(bean.getStemp_ID());
		answerReqBean.setSubTask_ID(bean.getSubTask_ID());

		ArrayList<QuestionAnswerBean> answer = answerDao.queryBySql(
				"select * from " + QuestionAnswerBean.TABLENAME + " where Task_ID='" + taskid + "' and SubTask_ID='"
						+ subTaskID + "' and Stemp_ID='" + bean.getStemp_ID() + "' and Submiter='" + userMobile + "'");

		ArrayList<AnswerReq> SubAnswer = new ArrayList<AnswerReq>();

		if (null != answer && answer.size() > 0) {
			// 把拉出的对应的StempID答案嫁到SubAnswer中
			for (int i = 0; i < answer.size(); i++) {
				QuestionAnswerBean answerBean = answer.get(i);
				AnswerReq answerReq = new AnswerReq();
				answerReq.setAnswer(answerBean.getAnswer());
				answerReq.setFileCount(answerBean.getFileCount());
				answerReq.setOtherAnswer(answerBean.getOtherAnswer());
				answerReq.setTaskQuestion_ID(answerBean.getTaskQuestion_ID());
				ArrayList<SifTaskQuestionBean> questionBeans = taskQuestionDao
						.queryBySql("select * from " + SifTaskQuestionBean.TABLENAME + " where Template_ID='"
								+ bean.getTemplate() + "' and TaskQuestion_ID=" + answerBean.getTaskQuestion_ID());
				SifTaskQuestionBean taskQuestionBean = questionBeans.get(0);
				answerReq.setQuestion(taskQuestionBean.getQuestion());
				answerReq.setQuestionType(taskQuestionBean.getQuestionType());
				answerReq.setOrder(taskQuestionBean.getOrderIndex());
				answerReq.setGPS(answerBean.getGPS());
				answerReq.setGPSTime(answerBean.getGPSTime());
				SubAnswer.add(answerReq);
			}
		}

		answerReqBean.setSubAnswer(SubAnswer);
		if (null != answerReqBean.getSubAnswer() && answerReqBean.getSubAnswer().size() > 0) {
			for (int i = 0; i < answerReqBean.getSubAnswer().size(); i++) {
				AnswerReq answerReq = answerReqBean.getSubAnswer().get(i);
				if (null != answerReq.getFileCount() && !"".equals(answerReq.getFileCount())
						&& !"0".equals(answerReq.getFileCount())) {
					for (int j = 0; j < Integer.valueOf(answerReq.getFileCount()); j++) {
						qCount++;
						//
						// sum++;
					}
				}
			}
		}
		try {
			tempjson = HttpJsonAdapter.getInstance().toJson(answerReqBean);
			Log.v("qqqq", tempjson);
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		FinalHttp fh = new FinalHttp();
		AjaxParams params = new AjaxParams();
		params.put("sid", ConstansJsonUrl.uploadAnswer_url);
		params.put("did", SinofaithUtil.did);
		params.put("dajson", tempjson);
		// 没有文件.提交answer传1
		if (qCount == 0) {
			params.put("taskfinally", "1");
		}

		fh.post(ConstansJsonUrl.REQUEST_URL, params, new AjaxCallBack() {

			@Override
			public void onStart() {
				// TODO Auto-generated method stub
				super.onStart();

			}

			@Override
			public void onLoading(long count, long current) {
				super.onLoading(count, current);
			}

			@Override
			public void onSuccess(Object t) {
				// mLoadingDialog.dismiss();
				super.onSuccess(t);
				try {
					BaseMessage baseMessage = HttpJsonAdapter.getInstance().get(t.toString(), BaseMessage.class);
					if (baseMessage.getResult().equals("0")) {

						// 没有文件
						if (qCount == 0) {
							afterSubmitUpdateLocalData(subTaskID, stempID);
							submitDeal(true);
						}
						// 有文件
						else {
							ArrayList<AnswerReq> answerReqs = answerReqBean.getSubAnswer();
							// answerReqs 每个题目的答案集合
							if (null != answerReqs && answerReqs.size() > 0) {
								for (int i = 0; i < answerReqs.size(); i++) {
									Log.i("TAG", "answerreqs" + answerReqs.size());
									AnswerReq answerReq = answerReqs.get(i);
									if (null != answerReq.getFileCount() && !"".equals(answerReq.getFileCount())
											&& !"0".equals(answerReq.getFileCount())) {
										String[] temps = answerReq.getAnswer().split("#");
										// 车架号下面一个题目的文件提交
										for (int j = 0; j < Integer.valueOf(answerReq.getFileCount()); j++) {
											Log.v("qqqq", temps[j]);
											if (null != temps[j] && !"".equals(temps[j])) {
												File file = new File(temps[j]);
												String fileName = file.getName();
												String fileType = fileName.substring(fileName.lastIndexOf(".") + 1,
														fileName.length());
												// 问题类型
												String qtype = "1";
												if ("3".equals(answerReq.getQuestionType())) {
													qtype = "1";
												} else if ("4".equals(answerReq.getQuestionType())) {
													qtype = "2";
												} else {
													qtype = "3";
												}
												UpLoadFileBean upBean = new UpLoadFileBean();
												upBean.setFile(file);
												upBean.setFileType(fileType);
												upBean.setGps(answerReq.getGPS());
												upBean.setOrder(answerReq.getOrder());
												upBean.setOtherAnswer(answerReq.getOtherAnswer());
												upBean.setqType(qtype);
												upBean.setStempId(stempID);
												upBean.setSubTaskId(subTaskID);
												upBean.setTaskId(taskid);
												upBean.setTaskQuestionId(answerReq.getTaskQuestion_ID());
												upInfos.add(upBean);
											}
										}
									}
								}
								upFileIterator();
							} else {
								submitDeal(false);
							}
						}

					} else {
						submitDeal(false);

					}
				} catch (Exception e) {
					submitDeal(false);
				}

			}

			@Override
			public void onFailure(Throwable t, int errorNo, String strMsg) {
				submitDeal(false);
				super.onFailure(t, errorNo, strMsg);
				Toast.makeText(ChildTaskActivity.this, strMsg, Toast.LENGTH_LONG).show();
			}
		});
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	void uploadFiles(final String taskid, final String subtaskid, final String tempid, final String questionid,
			final String ftype, final String suffix, final String order, final String desc, final File file,
			final String GPS) {

		FinalHttp fh = new FinalHttp();
		final AjaxParams params = new AjaxParams();
		params.put("sid", ConstansJsonUrl.uploadFile_url);
		params.put("did", SinofaithUtil.did);
		params.put("taskid", taskid);
		params.put("subtaskid", subtaskid);
		params.put("tempid", tempid);
		params.put("questionid", questionid);
		params.put("mobile", userMobile);
		params.put("ftype", ftype);
		params.put("suffix", suffix);
		params.put("order", order);
		params.put("desc", desc);
		params.put("finally", "0");
		if (qCount == 1) {
			params.put("taskfinally", "1");
		}
		params.put("GPS", GPS);
		try {
			S.FileParams(this, params, file);
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		Log.v("qqqq", ConstansJsonUrl.REQUEST_URL + "?" + params);
		fh.post(ConstansJsonUrl.REQUEST_URL, null, params, null, new AjaxCallBack() {
			@Override
			public void onStart() {
				super.onStart();
			}

			@Override
			public void onLoading(long count, long current) {
				// TODO Auto-generated method stub
				super.onLoading(count, current);
			}

			@Override
			public void onSuccess(Object t) {
				super.onSuccess(t);
				try {
					BaseMessage baseMessage = HttpJsonAdapter.getInstance().get(t.toString(), BaseMessage.class);
					Log.i("TAG", "upfile  " + baseMessage.getResult());
					if (baseMessage.getResult().equals("0")) {

						qCount--;
						success++;
						if (qCount == 0) {
							QuestionAnswerDao answerDao = new QuestionAnswerDao(ChildTaskActivity.this);
							Log.i("TAG", baseMessage.getDesc() + " upfile");
							String sql = "select * from " + QuestionAnswerBean.TABLENAME + " where Task_ID=" + taskid
									+ " and SubTask_ID=" + subtaskid;
							if (null != tempid && !"".equals(tempid)) {
								sql += " and Stemp_ID=" + tempid;
							}
							sql += " and Submiter=" + userMobile;
							List<QuestionAnswerBean> answerlist = answerDao.queryBySql(sql);
							if (null != answerlist && answerlist.size() > 0) {
								for (int i = 0; i < answerlist.size(); i++) {
									QuestionAnswerBean answerBean = answerlist.get(i);
									answerBean.setIsFinish("2");
									answerDao.update(answerBean);
								}
							}
							submitDeal(true);
						} else {
							if (upInfos != null && upInfos.size() > 0) {
								upInfos.remove(0);
								upFileIterator();
							}
						}
					} else {
						Log.i("TAG", "uploadfile else error");
						submitDeal(false);
					}
				} catch (Exception e) {
					Log.i("TAG", "uploadfile catch error");
					submitDeal(false);
				}
			}

			@Override
			public void onFailure(Throwable t, int errorNo, String strMsg) {
				submitDeal(false);
				Log.i("TAG", "uploadfile  onfailed");
				super.onFailure(t, errorNo, strMsg);
			}

		});
	}

	/**
	 * 提交完一道题后更新本地数据
	 */
	public void afterSubmitUpdateLocalData(final String subTaskID, final String stempID) {
		QuestionAnswerDao answerDao = new QuestionAnswerDao(this);
		String sql = "select * from " + QuestionAnswerBean.TABLENAME + " where Task_ID=" + taskid + " and SubTask_ID="
				+ subTaskID;
		if (null != stempID && !"".equals(stempID)) {
			sql += " and Stemp_ID=" + stempID;
		}
		sql += " and Submiter=" + userMobile;
		List<QuestionAnswerBean> answerlist = answerDao.queryBySql(sql);
		if (null != answerlist && answerlist.size() > 0) {
			for (int i = 0; i < answerlist.size(); i++) {
				QuestionAnswerBean answerBean = answerlist.get(i);
				answerBean.setIsFinish("2");
				answerDao.update(answerBean);
			}
		}
	}

	private void submitDeal(boolean norm) {
		if (norm) {
			if (answerList != null) {
				// 当只有一道题提交时
				if (answerList.size() == 1 && qCount == 0) {
					showToast("提交成功");
					if (sum > 0) {
						// showDialog("总共" + sum + "个文件，成功上传" + success + "个");
						showDialog(this, sum, success);
					}
					pDialog.dismiss();
					// getUploadCheck();
				}
				// 大于1时
				else if (answerList.size() > 1) {
					pDialog.setText("正在提交,剩余" + (answerList.size() - 1) + "未提交");
					if (qCount == 0) {
						// 递归提交
						recursionAnswer();
					} else {
						// 继续执行

					}
				}

			}
		} else {
			pDialog.dismiss();
			// showDialog("提交失败,剩余" + (answerList.size() - 1) + "未提交");
			showDialog(this, sum, success);
		}
	}

	private void upFileIterator() {
		if (upInfos != null && upInfos.size() > 0) {
			UpLoadFileBean bean = upInfos.get(0);
			uploadFiles(taskid, bean.getSubTaskId(), bean.getStempId(), bean.getTaskQuestionId(), bean.getqType(),
					bean.getFileType(), bean.getOrder(), bean.getOtherAnswer(), bean.getFile(), bean.getGps());
		}
	}

	private Toast mToast;

	public void showToast(String text) {
		if (mToast == null) {
			mToast = Toast.makeText(this, text, Toast.LENGTH_SHORT);
		} else {
			mToast.setText(text);
			mToast.setDuration(Toast.LENGTH_SHORT);
		}
		mToast.show();
	}

	public void showDialog(String text) {
		new AlertDialog.Builder(this).setMessage(text).setNeutralButton("确定", null).setCancelable(false).show();
	}

	public static void showDialog(final Context context, final int sum, final int success) {
		final String text = "总共" + sum + "个，成功" + success + "个，失败" + (sum - success) + "个";
		new AlertDialog.Builder(context).setMessage(text).setNeutralButton("确定", null).setCancelable(false).show();
	}
}
